在进行代码审查时,我最近遇到过这样的代码块:
const promises = [];
const data = [];
for (let piece of pieces) {
for (let chunk of piece) {
promises.push(execute(chunk)); //execute returns a promise which is not yet fulfilled
}
data = await Promise.all(promises);
}
Run Code Online (Sandbox Code Playgroud)
这pieces是一个数组数组.请注意,由于某些约束,我们不能同时使用await所有Promise,因此这种类型的分块.
在我的反馈中,我写道,这似乎是一个反模式,因为我们也在等待在前几次迭代中解决的 Promises ,以下是处理这种情况的正确方法:
const data = [];
for (let piece of pieces) {
const promises = [];
for (let chunk of piece) {
promies.push(execute(chunk)); //execute returns a promise which is not yet fulfilled
} …Run Code Online (Sandbox Code Playgroud)