首页 > 解决方案 > 无法理解 async/await nodejs

问题描述

好的,所以我在理解 nodejs 中的 async/await、Promises 等如何工作时遇到了麻烦,这是我第一次使用异步语言进行编程。

我在这里尝试做的基本上是从猫鼬模型“SecSolution”中选择一个随机条目。当前,当返回 arr 时,它是空的,并且在打印顶部的调试之前打印底部的调试消息。我只希望函数在获得其值后返回“arr”。

async function getRandomCardIds(deckIdentifier, cardCount) {
    let arr;
    switch (deckIdentifier) {
        case 102:
            await SecSolution.count().exec(async function (err, count) {
                let promises = [];
                var random = Math.floor(Math.random() * count);
                for (let i = 0; i < 2; i++) {
                    promises.push((await SecSolution.findOne().skip(random).lean())._id);
                }
                arr = await Promise.all(promises);
                debug("This gets printed second" + arr);
            });
            break;
    }
    debug("this gets printed first");
    return arr;
}

提前致谢!

标签: javascriptnode.jsasynchronousmongoosepromise

解决方案


async使用/时不要使用回调await。(当使用简单的 Promise 时, then使用回调)。此外,您不应该使用await仍然需要作为承诺对象的承诺,将其传递给Promise.all. 你的代码应该是

async function getRandomCardIds(deckIdentifier, cardCount) {
    switch (deckIdentifier) {
        case 102:
            const count = await SecSolution.count(); // a promise(like object)
            let promises = [];
            var random = Math.floor(Math.random() * count);
            for (let i = 0; i < 2; i++) {
                promises.push(SecSolution.findOne().skip(random).lean());
            }
            let arr = await Promise.all(promises);
            debug("This gets printed second" + arr);
            return [arr[0]._id, arr[1]._id];
            break;
    }
    debug("this gets printed first");
    return undefined;
}

除了访问_id结果数组中对象上的 s 之外,您还可以直接转换承诺(类似于您尝试使用 的await):

promises.push(SecSolution.findOne().skip(random).lean().then(card => card._id));

推荐阅读