【发布时间】:2021-09-01 12:09:26
【问题描述】:
我花了太多时间来寻找这个错误。所以这是我的代码。显然,当我使用 push 时,数组最终是完整的,但是当我使用 concat 时,估计有 50% 的机会我不会得到所有连接的项目,因为 concats 似乎同时运行。我不相信这是可能的,所以任何人都可以向我解释为什么版本 1 有效,但版本 2 无效。
let employments: any[] = [];
let companyIds = ['Id1', 'Id2']
await Promise.all(
companyIds.map( async ( companyId ) => {
const companies = await getCompaniesWithId(companyId);
// VERSION 1
employments.push( ...(await mergeWithOtherSource( companies )) );
// VERSION 2
employments = employments.concat( await mergeWithOtherSource( companies ));
} )
);
// VERSION 1 always returns 3 expected items as are in the databases
// VERSION 2 RANDOMLY returns between 1 and 3 items
return employments.length
【问题讨论】:
-
companyIds.map不返回任何内容。没有什么可以等待的。.map旨在将一个数组映射到另一个数组。您只是推送到一个不正确的外部数组。 -
@zero298
companyIds.map确实返回Promises (Promise<void>[]) -
@OP 你能试着把
await mergeWithOtherSource( companies )移到concat之外吗? -
companyIds.map确实返回承诺:jsfiddle.net/4db6ecxg/1 -
@appleapple 将 await 放在 concat 之外也可以解决问题。似乎 concat 在等待承诺之前引用了原始数组。