猫鼬查找不等待完成

时间:2021-01-04 12:56:07

标签: javascript node.js mongodb mongoose

为什么这段代码不等待查找完成然后返回。它在查找完成之前返回一个空数组。

const findAllUsers = () => {
    const channelNames = [];

    ATwitchStreamer.find({}, (err, res) => {
        console.log(res)
        res.forEach((user) => {
            channelNames.push(user.username);
        });
    }).then(r =>
        return channelNames);
    return channelNames;
};

2 个答案:

答案 0 :(得分:1)

find 方法是一个异步函数 所以你可以使用 async/await

const findAllUsers = async() => {
    const channelNames = [];

    await ATwitchStreamer.find({}, (err, res) => {
        console.log(res)
        res.forEach((user) => {
            channelNames.push(user.username);
        });
    })
    return channelNames;
};

答案 1 :(得分:0)

ATwitchStreamer.find 是一个 Promise。你通过返回承诺链来解决这个问题:

return ATwitchStreamer.find(...)