1

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.

1 Answer 1

1

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;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.