【发布时间】:2021-10-30 00:47:10
【问题描述】:
我有一个 Promise 函数的嵌套数组。例如:
let callSet = [
[ func1 , func2 , func3],
[ func4 , func5 , func6],
[ func7 , func8 , func9],
]
await func1() 的响应将在以下结构中:
{
data : [ {id: 1} , {id:2}],
status: 400
}
我想在 for 循环中运行它,以便它们按顺序批量运行,并在数据进入时将数据增量加载到数组中。尝试了下面的代码,但我不知道该怎么做:
const finalData = [];
private asyncForEach(PromiseGroups): Promise<any> {
return PromiseGroups.reduce(async (acc, cItem) => {
const results = await acc;
const res = await Promise.all(cItem) as any;
finalData = [...finalData , ...[].concat(...res.map(r => r.data))];
return results
}, Promise.resolve([]))
}
我想将其加载为:
[ {id: 1}, {id:2} , {id: 3} ..... ]
随着 Promise 的解决,这应该会得到更新
我想等到 func1 , func2 , func3 解决后再转到 func4 , func5 , func6 。一旦我得到func4 , func5 , func6的数据,我想用func1 , func2 , func3的数据推送它
【问题讨论】:
-
在 reducer 回调中等待不会导致
reduce函数为await回调 -
您能否详细说明按顺序和增量批量运行。我怀疑你的功能比 ikhvjss 答案中的要多。
-
@Newbie:是的,你是对的,我想等到
func1 , func2 , func3解决后再转到func4 , func5 , func6。一旦我得到`func4 , func5 , func6`` , I want to push it with the data offunc1,func2,func3`的数据` -
@JuanMendes:请您指导正确的方法
-
最简单的方法?不要使用
reduce,只需使用for of填充一系列承诺。见stackoverflow.com/questions/41243468/…
标签: javascript typescript async-await promise