不能在MongoDB Model上使用async / await,即使它返回Promise?

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

我有一个函数获取用户库存,然后它的每个元素qazxsw poi属性与从qazxsw poi获得的价格。

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

price

现在根据Mongo Docs,您可以使用回调调用Price.findOne,但您也可以使用promise(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 }); 调用它,因为它返回一个promise。但是,唉,我收到的错误是这样的:

.then()

它没有await关键字,但我不能像那样使用它,因为那时我会遇到异步性问题。

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

javascript node.js mongodb mongoose mongodb-query
1个回答
0
投票

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

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