javascript - 试图在 JS 中的数组中获取值,该数组位于函数外部且该函数是异步的

标签 javascript node.js async-await sequelize.js

所以基本上我在 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 执行之后运行,而是在此之前运行,因为 startasync 而你没有为它运行 await。这意味着 start 被添加到 event loop 并且,即使 trips.forEach 被等待并执行,它里面的 function 也不会被等待。因此,从技术上讲,第二个控制台日志在 forEach 之后,但在任何 start 调用完成之前执行。
enter image description here

关于javascript - 试图在 JS 中的数组中获取值,该数组位于函数外部且该函数是异步的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64020929/

相关文章:

node.js - Azure DB 断开连接和连接超时

python-3.x - 如何使用 asyncio 优雅地超时

asp.net - 将对象数组从 javascript 发送到 Web 服务的最佳方法是什么?

javascript - Ext 4 ComboBox自定义触发器

node.js - ExpressJS - 带参数的路由器模块

javascript - 在 Angular 5 中设置 header

unit-testing - 测试 future 和流,我如何创建一个假的上下文?

node.js - 如何使用 ES7 语法从 Node.js VM 脚本检索异步结果

javascript - 在搜索图标和取消图标之间切换

javascript - JS中如何添加两个变量?