所以基本上我在 start 函数内推送名为 TripsData 的 ArrayList 中的值,但是一旦我退出函数它就会变空,所以我不能进一步超出。
其中 trips 只是一个数组 [1,2,3,4]
代码如下...
const TripsData = []; // I need to push data in this array
await trips.forEach((trip) => {
async function start() {
const url = await TripMedia.findOne({ // i get my url here
where: { tripID: trip },
})
.then((result3) => {
const url = result3.mediaURL;
return url;
})
.catch((error) => {
console.log(error);
});
const subject = await TripDetails.findOne({ // i get my subject here
where: { tripID: trip },
})
.then((result3) => {
const subject = result3.subject;
return subject;
})
.catch((error) => {
console.log(error);
});
TripsData.push({
tripId: trip,
mediaURL: url,
subject: subject,
}); // The value is getting pushed here
}
start();
});
console.log(TripsData) // If i try to get data here its not present
Reply.push({
"locationId":location,
"locationName": dict[location],
"trips": TripsData
}) // so the value of tripsData is like [] only ... how to get data
值来了TripsData.push({
tripId: trip,
mediaURL: url,
subject: subject,
});
但是 forEach 之外的值结束它变空了吗?问题是为什么会这样以及如何解决
预先感谢您的上帝级帮助
最佳答案
你误解了代码。第二个 console.log
不会在 function
执行之后运行,而是在此之前运行,因为 start
是 async
而你没有为它运行 await
。这意味着 start 被添加到 event loop 并且,即使 trips.forEach
被等待并执行,它里面的 function
也不会被等待。因此,从技术上讲,第二个控制台日志在 forEach
之后,但在任何 start
调用完成之前执行。
关于javascript - 试图在 JS 中的数组中获取值,该数组位于函数外部且该函数是异步的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64020929/