【问题标题】:Cannot use async/await on MongoDB Model, even though it returns Promise?不能在 MongoDB 模型上使用 async/await,即使它返回 Promise?
【发布时间】:2018-02-28 20:39:24
【问题描述】:

我有一个获取用户库存的函数,然后它的每个元素的 price 属性以及从 Price Collection 获取的价格。

在这里(不是整个功能,但我在这里遇到了错误):

async function updateUserInventory(inventory, userDetails, socket) {
    let newArray = await inv.map(item => {
        let price = await Price.findOne({ market_hash_name: item.market_hash_name });
        return {
            price: price.price
        }
        logger.debug(JSON.stringify(item, null, 2));
    });

    socket.emit('user inv', { items: newArray });

现在根据 Mongo 文档,您可以使用回调调用 Price.findOne,但您也可以使用承诺 (.then()) 调用它。这意味着您也应该能够使用await 调用它,因为它返回一个承诺。但是,唉,我收到了一个错误:

D:\code\some-api\api\helpers\priceUpdater.js:129
        let price = await Price.findOne({ market_hash_name: item.market_hash_name });
                          ^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)

它在没有await 关键字的情况下工作,但我不能那样使用它,因为那样我会遇到异步问题。

也许我没有正确使用 async/await。有什么帮助吗?

【问题讨论】:

  • 你有什么版本的节点?
  • D:\code\some-api>node -v v8.9.4
  • await 只能在 async 函数中使用,而您的 map 回调不是。
  • 看起来您使用的是 Mongoose 模型,对吧?
  • 显然不是。最接近的函数必须是async。感觉有点傻,但这就是它的实现方式。

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

对于遇到相同问题的任何人(在 .map 或任何 JS 数组迭代器函数中使用 await),我通过在 .map 上调用 Promise.all 来解决它,然后在元素上调用 async迭代。感谢@georg 的指点。

async function updateUserInventory(inventory, userDetails, socket) {
    let newArray = await Promise.all(inv.map(async (item) => {
        let price = await Price.findOne({ market_hash_name: item.market_hash_name });
        return {
            price: price.price
        }
        logger.debug(JSON.stringify(item, null, 2));
    }));

    socket.emit('user inv', { items: newArray });

【讨论】:

猜你喜欢
  • 2017-09-11
  • 2022-01-22
  • 2022-08-22
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
相关资源
最近更新 更多