【问题标题】:Waiting for all asyc processes to finish in a loop等待所有 asyc 进程循环完成
【发布时间】:2021-02-06 02:55:12
【问题描述】:

我有一个循环来比较 2 个数据库。在循环结束时,我正在保存进行了多少更改。 我需要确保在一切完成后运行“LogResults”。

这样的东西可以工作,但由于“获取”上的“等待”而速度很慢。

for( let i = 0; i < json.data.length; i++ )
{
    var newEntry = new PopulateNewEntry( ... );
    entryArray.push( newEntry );

    await wixData.get( "MyDatabase", newEntry._id )     // <--- Slow
        .then( async results => {

            if( results === null )
            {
                //...Async process to write new entry to database.
            }
            else if( results are different )
            {
                //...Async process to modify entry in database.
            }
        })
}
LogResults();

我在这里看到了使用 promise 数组并等待所有人完成的方法。但我想我不确定如何在履行承诺的同时使用它。我发现的所有示例都没有在正在等待的函数上使用“.then”。

如下所示,但这不起作用。似乎永远不会完成“等待”。

var pending = [];

for( let i = 0; i < json.data.length; i++ )
{
    var newEntry = new PopulateNewEntry( ... );
    entryArray.push( newEntry );

    const promise = wixData.get( "MyDatabase", newEntry._id )
        .then( async results => {

            if( results === null )
            {
                //...Async process to write new entry to database.
            }
            else if( results are different )
            {
                //...Async process to modify entry in database.
            }
        })

    pending.push( promise );
}

const array = await Promise.all( pending );

LogResults();

我在这里做错了什么?

【问题讨论】:

  • 看看link
  • 你不是将一个待处理的承诺推送到一个数组,而是一个已经实现的承诺,因为你已经将.then() 链接到它。

标签: javascript async-await


【解决方案1】:

@Terry 已经在 cmets 中给了你答案,但让我扩展一下……

正如他在链接.then 时已经提到的那样,它会返回一个“已解决”的承诺。 Promise.all 不是你想要的。

你应该做的是这样的:

const promise = wixData.get( "MyDatabase", newEntry._id );
promise.then(...);
pending.push(promise);

此外,除非您真的需要同步行为,否则为什么不使用 await 代替 Promise.all 只是将 .then 链接到它?只是一个想法。

如果您想要获得最佳性能,请不要等待每个 Promise 一个接一个地完成,就像您在第二个示例中所做的那样,调用所有 Promise,然后等待它们全部完成。

【讨论】:

  • 很好的解释(也感谢特里)。我没有意识到链接 '.then' 改变了返回行为。更改为您的建议效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 2012-09-30
相关资源
最近更新 更多