M
M
Maxim Korolsky2016-08-12 00:59:19
JavaScript
Maxim Korolsky, 2016-08-12 00:59:19

How to array promises in redux?

export function homePageProfileAction(list, name) {
    return (dispatch) => {
        dispatch(homePageProfileFetchId(list, name));

        let promise = list.map(v => {
            console.log(getUserHome(v));
            return getUserHome(v).then(id => {
                dispatch(homePageProfileFetchSuccess(id, v));
            });
        });

        // Promise.all([promise])
        //     .then((res) => {
        //         console.log(res);
        //         dispatch(homePageProfileFetchSuccess(res, "top"));
        //     })
        //     .catch(err => {console.log(err); });
    };
}

There is such a function. I am getting an array with id. I execute a request to the database (this is the promise)
But I would like everything to be executed simultaneously and dispatch one success, instead of 4
Promise.all I tried, but something loops there. I can't understand what

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nd0ut, 2016-08-12
@SuperPosan

export function homePageProfileAction(list, name) {
    return (dispatch) => {
        dispatch(homePageProfileFetchId(list, name));

        const promises = list.map(v => getUserHome(v));

        Promise.all(promises)
            .then((res) => {
                dispatch(homePageProfileFetchSuccess(res, "top"));
            })
            .catch(err => {console.log(err); });
    };
}

V
Vladimir Shestakov, 2016-08-12
@boolive

Promise.all will return an array of responses from all executed requests. See what you return in then of each request and how you process it afterwards.

export function homePageProfileAction(list, name) {
    return (dispatch) => {
        dispatch(homePageProfileFetchId(list, name));

        let promise = list.map(v => {
            return getUserHome(v);
        });

        Promise.all(promise)
             .then((ids) => {
                 console.log(ids);
                 //dispatch(homePageProfileFetchSuccess(res, "top"));
             })
             .catch(err => {console.log(err); });
    };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question