繁体   English   中英

即使它返回Promise,也无法在MongoDB模型上使用async / await吗?

[英]Cannot use async/await on MongoDB Model, even though it returns Promise?

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

在这里(不是整个功能,但这里出现错误):

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 Docs,您可以使用回调函数调用Price.findOne,但也可以使用promise( .then() )进行调用。 这意味着您还应该可以在await调用它,因为它会返回一个promise。 但是a,我收到一个错误,它是这样的:

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关键字就可以工作,但是我不能那样使用它,因为那样我会遇到异步问题。

也许我没有正确使用异步/等待。 有什么帮助吗?

对于遇到相同问题的任何人(在.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 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM