有个疑问,为什么数组中 forEach、Map 这样的方法中,不能使用 await 呢?
发布于 6 年前 作者 varscc 4212 次浏览 来自 问答

为什么数组中 forEach、Map 这样的方法中,不能使用 await 呢?

10 回复

因为规范没有约定。 await for of 才提出

现在可以这样用:

const results = await Promise.all(dataList.map(x => {
  return asyncHandler(x);
}));

或者用 https://github.com/sindresorhus/promise-fun

作用域问题。用 for..of

@atian25 好的,感谢

@alsotang 原始for也可以, 感谢

@varscc 一个并行一个串行

            await Promise.all(companyList.map(async value => {
                if(value.status === -2){
                    let companyID = value.companyID;
                    let data = {
                        companyID,
                        Nlimit:1,
                        Ncount:1
                    }
                    let auditOpinion = await ctx.service.companyRecordService.findAll(data)
                    if(auditOpinion.length !== 0 && auditOpinion[0].auditOpinion){
                        auditOpinion = auditOpinion[0].auditOpinion;
                        value['auditOpinion'] = auditOpinion;
                    }
                }
                return value
            }))

因为 forEach 每一次循环都创造了 async 函数, 瞬间生成了 array.length 个 async 函数,async 函数内 await 才是“阻塞”,所以成了并发。

回到顶部