如何等待异步?而为什么等待是行不通的?

问题描述 投票:0回答:1

这里是我路由器的一部分:

        if (limit <= 100) {
        let id = jwt.verify(req.cookies.tokenlogin, config.get('jwtSecret')).userId
        const results = await User.paginate({ $and: [{ _id: { $ne: id }, fullname: { $regex: search, $options: '-i' } }] },
            { page: page, limit: limit, customLabels: myCustomLabels, lean: true, select: '-email -password' });
        let paginator = results.paginator;
        let arrayRes = results.items;
        await arrayRes.forEach(async (current, i) => {
            await User.findOne({ _id: id }, async (er, rs) => {
                current['followed'] = await rs.followings.includes(current.id);
            })
        })
        res.status(200).json({ items: arrayRes, paginator: paginator })
    }

我使用了await,但是它不起作用,服务器总是向客户端发送未更新的数组。如何在响应中发送修改后的数组?

javascript node.js asynchronous
1个回答
-1
投票

您可以改用Promise。

这样的作品

((您的第一个任务)。然后(()=>您的第二个任务)]

© www.soinside.com 2019 - 2024. All rights reserved.