[英]Cannot use async/await on MongoDB Model, even though it returns Promise?
I have a function which gets a user inventory, and then each of its element's price
property with the Price gotten from a Price Collection
. 我有一个获取用户库存的函数,然后使用从Price Collection
获取价格的每个元素的price
属性。
Here it is (not the whole functon, but I'm getting the error here): 在这里(不是整个功能,但这里出现错误):
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 });
Now as per the Mongo Docs, you may call Price.findOne with a callback, but you also can call it with a promise ( .then()
). 现在,根据Mongo Docs,您可以使用回调函数调用Price.findOne,但也可以使用promise( .then()
)进行调用。 Which means you SHOULD be able to also call it with await
since it returns a promise. 这意味着您还应该可以在await
调用它,因为它会返回一个promise。 But alas, I'm getting an error which is this: 但是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)
It works without the await
keyword, but I cannot use it like that because then I'll have problems with asynchronicity. 它没有await
关键字就可以工作,但是我不能那样使用它,因为那样我会遇到异步问题。
Maybe I am not using async/await properly. 也许我没有正确使用异步/等待。 Any help? 有什么帮助吗?
For anyone that encounters the same problem (using await
inside a .map
or any JS array iterator function), I solved it by calling Promise.all
on the .map
and then async
on the element being iterated. 对于遇到相同问题的任何人(在.map
或任何JS数组迭代器函数中使用await
),我通过在.map
上调用Promise.all
然后在要迭代的元素上进行async
来解决此问题。 Thanks to @georg for the pointer. 感谢@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.