javascript - 如何使用异步调用修改一个数组项
问题描述
我想在循环中使用 await 来修改函数,但发现由于我在 foreach 循环中进行的调用是异步的,因此它无法按预期工作,并且我的表最终为空。因此,我认为最好的选择是使用 map ,但我无法使其按预期工作:
optionsRaw.forEach(async raw => {
const option = new Option();
option.id = raw['id'];
option.nbMax = raw['nb_max'];
option.disabled = (await this.countAnswer(option.id))>=option.nbMax;
options.push(option);
});
return options;
当我有这个等待时选项是空的 我可以添加一个'then'或其他东西吗?
否则,我可以这样做:
options = options.map(async option=>{
option.disabled = option.nbMax>0 && (await this.countAnswer(option.id, id_challenge))>=option.nbMax;
return option;
})
return options;
“类型承诺不可分配给类型 Option[]”
但现在没有成功,我想我肯定会错过这张“地图”的东西
解决方案
您需要使用Promise.all
,它返回一个新的 Promise,该 Promise 由传递的 Promise 的一组完成值来完成,或者以第一个被拒绝的 Promise 的原因拒绝。我们可以在这里看到 MDN 文档。
所以,像这样用 Promise.all 包装你的代码,
options = Promise.all(options.map(async option=>{
option.disabled = option.nbMax>0 && (await this.countAnswer(option.id, id_challenge))>=option.nbMax;
return option;
}));
return options;