我有一个项目数组,我需要为数组中的每个项目做一个 Axios 帖子。每个项目都依赖于从前一项返回的数据,因此我需要它们同步执行。我面临的问题是我不知道数组中将有多少个项目。如果我知道数组计数,我可以执行以下操作:
let my_array = [34, 44, 72];
axios.post(
'url-to-get-data',
{
post_data_1: my_array[0]
}
).then(res => {
axios.post(
'url-to-get-data',
{
post_data_1: my_array[1],
post_data_2: res.data
}
).then(res => {
//Third axios post.....
}
).catch();
}
).catch();
有谁知道我如何实现这一目标?
你本质上是在问如何链接(未知长度的(异步工作。
使用承诺(和递归(:
let asyncDec = count => Promise.resolve(count - 1);
let handler = count => {
console.log('handled', count);
if (count)
return asyncDec(count).then(handler)
};
asyncDec(10).then(handler);
使用 await/async:
let asyncDec = async count => count - 1;
let main = async () => {
let count = 10;
while (count >= 0) {
console.log('handled', count)
count = await asyncDec(count);
}
};
main();