能在for循环中写await"/>
不能在for循环中写await
我知道这是一个重复的问题,但我仍在写我的查询
意外问题
await
在循环内
const createChartPanel = async (data) => {
let panel = []
let promises = []
for (let a = 0.0; a < totalMacroFactorCount; a += /* increment */) {
//some bunch code here
let promise = addCharts(/* your arguments */).then(() => {
panel.push(chartPanel)
});
promises.push(promise)
a = parseFloat(a + 1).toFixed(1);
}
await Promise.all(promises) // await for all promises to finish
return panel;
}
在addChart完成promises.push(promise)之前,我应该如何调用promises.push(promise)一次addChart过程完成
const addCharts = async (data, chartTable, barColor, orangeBar, maroonBar, darkBlueBar, chartHeight, isFirstRow) => {
// some code
const maxHeight = _.maxBy(_.flatten(modifiedData), 'y');
const promisesBenchmark = modifiedData.map(async (subArr, index) => {
const currentChart = await getSVG(index % 2, subArr, isStrScore, maxHeight?.y);
return currentChart;
});
const svgs = await Promise.all(promisesBenchmark);
let nidx = 0;
for (const svg of svgs) {
chartTable[nidx + 1].table.body.push([{
svg: svg, alignment: 'center', border: [false, false, false, true],
borderColor: '#41ABE0', borderWidth: 0.5,
width: chartWidth, height: chartHeight, fillColor: (nidx % 2 ? 'white' : '#f2f2f3')
}]);
nidx++;
}
};
这里的 SVG 图像没有在 addChart 中完全创建,因此产生了问题
回答如下:如果您想要等待由循环(或其他方式)创建的多个承诺,则需要将这些承诺捕获到
Array
中,然后使用Promise.all
函数。
要在 promise 解决后采取一些行动,您需要对上述 promise 使用
.then
方法(或者您可以将其移动到单独的异步函数,在那里您相应地等待这两个动作)。
const createChartPanel = async (data) => {
let panel = []
let promises = []
for (let a = 0.0; a < totalMacroFactorCount; a += /* increment */) {
//some bunch code here
let promise = addCharts(/* your arguments */).then(() => {
panel.push(chartPanel)
});
promises.push(promise)
}
await Promise.all(promises) // await for all promises to finish
return panel;
}
更多推荐
不能在for循环中写await
发布评论