我有一个名为codigo
的数组,我.push
它在.map()
内的一些数据。
当我将 console.log(codigo);
放在 map()
内时,结果是正确的,但是当我将控制台日志放在 .map( )
结果为空。
let pre = '';
let cod = [];
devPre.map(async (item) => {
pre = await models.pres.findOne({
where: {
id: item.pres_id,
},
});
cod.push(pre.codPre);
console.log(cod); // This return the correct values
});
console.log(cod); // This return [], this is my error
我需要外部 console.log
返回正确的值,就像其他 console.log
一样。
最佳答案
等待 Promise.all 您正在检索的所有值:
const allPromises = devPre.map((item) => {
return models.pres.findOne({
where: {
id: item.pres_id,
},
});
});
const pres = await Promise.all(allPromises);
const cod = pres.map(pre => pre.codPre);
关于javascript - 如何使用 .push 保存数组以在 .map() 之外异步读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49523619/