【发布时间】: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