Is it possible to use axios.all with a then() for each promise?

与世无争的帅哥 提交于 2019-11-27 20:15:16

Okay, so I found a way to do what I needed without using using a then on each get. Since the params passed in to axios.get contain enough info to determine the save location, and since I can read the params back from the response, I can do something like the following:

let promises = [];

for (let i = 0; i < requests.length; i++) {
    promises.push(axios.get(request[i].url, { params: {...} }));
}

axios.all(promises)
    .then(axios.spread((...args) => {
        for (let i = 0; i < args.length; i++) {
            myObject[args[i].config.params.saveLocation] = args[i].data;
        }
    }))
    .then(/* use the data */);

This ensures all the data is received and saved to the object before it is used.

trincot

If the behaviour of your second attempt is indeed like that, then that would be an indication that axios is not Promise/A+ compliant. The then callback's return value must be the value with which the promise returned by that then is fulfilled. Since that is the promise you push into the array, the value that axios.all would return for that promise can only be known by executing the then callbacks first.

Event though you do not return a value explicitly in the then callback, this does not affect the above rule: in that case the return value is undefined and it is that value that should be provided by axios.all once the corresponding promise is resolved.

See in particular the rules 2.2.7, 2.2.7.1, 2.3.2.1, 2.3.2.2 in the specs of Promise/A+).

So I would suggest using a Promise/A+ compliant promise implementation instead. There are several other libraries, like for instance request-promise.

Alternatively, you could use the native ES6 Promise implementation, and promisify the http.request method yourself.

ES6 offers Promise.all which guarantees to provide the resolved values in the same order as the promises were provided.

your initial code could work normally as intended if you pass the promises to your array attached with their respective then function

let promises = []; // array to hold all requests promises with their then
for (let i = 0; i < requests.length; i++) {
    // adding every request to the array
    promises.push(
        axios.get(request[i].url, { params: { ...} })
            .then(response => { myObject[request[i].saveLocation] = response.data; })
    );
}
// Resolving requests with their callbacks before procedding to the last then callback
axios.all(promises).then(/* use the data */);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!