如何使用 .push 保存一个数组以在 .map() 之外读取,异步?
How to save with .push an array to read outside of .map(), with async?
我有一个名为 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
returns 具有正确的值,就像其他 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);
我有一个名为 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
returns 具有正确的值,就像其他 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);