首页 > 解决方案 > 等待在没有承诺的情况下执行一组操作

问题描述

我试图找出一种使用await以下方法的方法:我循环遍历一个数组。然后我检查每个项目的一些条件。如果条件适用,那么我执行异步操作。这是它的样子:

for(exampleItem in exampleArray) {
    const condition = SOME_SERVER_OPERATIONS_TO_CHECK;
    if(condition) {
        await AN_ASYNC_OPERATION
    }
}
 
// More code to execute

但是,这些操作执行是独立的。但是-我不想在// More code to execute所有执行完成之前执行。

我想做这样的事情:

await for(exampleItem in exampleArray) {
    const condition = SOME_SERVER_OPERATIONS_TO_CHECK;
    if(condition) {
        AN_ASYNC_OPERATION
    }
}

// More code to execue

意思是,我不想在所有完成// More code the execute后才执行。AN_ASYNC_OPERATION这就像Promise.all. 有没有办法只用await?

标签: javascript

解决方案


你可以做

const operations = [];
for(exampleItem in exampleArray) {
   const condition = SOME_SERVER_OPERATIONS_TO_CHECK;
   if(condition) {
        operations.push(AN_ASYNC_OPERATION);
   }
}
await Promise.all(operations);

// more code to execute

推荐阅读