最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

不能在for循环中写await

网站源码admin42浏览0评论

不能在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;
}  

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论