Skip to content Skip to sidebar Skip to footer

Waiting For All Promises Called In A Loop To Finish

I'm using the axios promise library, but my question applies more generally I think. Right now I'm looping over some data and making a single REST call per iteration. As each call

Solution 1:

You need to collect all of your promises in an array and then use Promise.all:

// Example of gathering latest Stack Exchange questions across multiple sites// Helpers for exampleconst apiUrl = 'https://api.stackexchange.com/2.2/questions?pagesize=1&order=desc&sort=activity&site=',
    sites = ['stackoverflow', 'ubuntu', 'superuser'],
    myArrayOfData = sites.map(function (site) {
        return {webAddress: apiUrl + site};
    });

functionconvertToStringValue(obj) {
    returnJSON.stringify(obj, null, '\t');
}

// Original question codelet mainObject = {},
    promises = [];

myArrayOfData.forEach(function (singleElement) {
    const myUrl = singleElement.webAddress;
    promises.push(axios.get(myUrl));
});

Promise.all(promises).then(function (results) {
    results.forEach(function (response) {
        const question = response.data.items[0];
        mainObject[question.question_id] = {
            title: question.title,
            link: question.link
        };
    });

    console.log(convertToStringValue(mainObject));
});
<scriptsrc="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>

It's described in axios docs (Performing multiple concurrent requests section).

Before May 2020 it was possible to do with axios.all(), which is now deprecated.

Post a Comment for "Waiting For All Promises Called In A Loop To Finish"