javascript - 等待在没有承诺的情况下执行一组操作
问题描述
我试图找出一种使用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?
解决方案
你可以做
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
推荐阅读
- python - 在货币价值上放置适当的零
- javascript - 节点将函数名称从文件推送到数组
- android - FragmentManager 在 Fragment 内执行 biometricPrompt?.authenticate(promptInfo) 时已经在执行事务
- c - 在 C 中实现向量(动态数组) - 函数和主文件
- php - 如何修复 Heroku 无法识别我要部署的 PHP Web 应用程序
- ios - NSURLSession/NSURLConnection HTTP 加载失败 (kCFStreamErrorDomainSSL, -9802) Xamarin.Forms IOS
- excel - Excel:如何在自动更新的文件夹中制作文件夹列表
- c - 在 C 中操作链表时如何解决此段错误问题?
- r - 每周从 user_id 和 date 查找新的活跃用户
- html - 背景图像调整大小改变了android中的视图