myTest532 myTest532
myTest532 myTest532

Reputation: 2391

React/Redux and JavaScript Promise.all

I'm having an issue with Promise.all in React. I'm creating promises for my axios request and at the end run a Promise.all to dispatch all the data.

Here is my method where I create the Promises:

function promiseLoad(nameID, uID, caption) {
    return new Promise( () => {
        axios.get(`${URL}/users/${uID}/name/${nameID}`)
            .then(res => {
                let obj;
                if(res.data !== -1) {
                    obj = {
                        fullName: res.data,
                        caption: caption
                    };
                }
                return obj;
        });
    });
}

Then, in my export method, I run the Promise.all before dispatch it to the reducer.

export const loadUsers = (users, uID) => {
    return dispatch => {
        let promises = [];
        imgs.forEach(element => {
            promises.push(promiseLoad(element.id, uID, element.caption));
        });
            console.log('Promises');
            console.log(promises);
        Promise.all(promises)
            .then(res => {
                console.log('here');
                console.log(res);
                dispatch(getUsers(res));
        });
    }
}

The getUsers just a helper method to return the type/action

export const getUsers = (res) => {
    return {
        type: actionTypes.GET_USERS,
        payload: res
    }
}

When I run the code, I can see in the log:

Promises
Array(10) // array with 10 pending promises

The logs inside the .then() method of Promise.all, never runs.

Upvotes: 1

Views: 182

Answers (1)

richytong
richytong

Reputation: 2462

axios.get returns a promise already, so you don't need to wrap it in the Promise constructor. Note that if you do construct a Promise, to avoid it never resolving, you must at least call resolve in the executor. In your case, promiseLoad was returning a Promise that never resolved, so you weren't seeing those logs.

function promiseLoad(nameID, uID, caption) {
    return axios.get(`${URL}/users/${uID}/name/${nameID}`)
        .then(res => {
            let obj;
            if(res.data !== -1) {
                obj = {
                    fullName: res.data,
                    caption: caption
                };
            }
            return obj;
    });
}

Upvotes: 1

Related Questions