javascript - 无法理解 async/await nodejs
问题描述
好的,所以我在理解 nodejs 中的 async/await、Promises 等如何工作时遇到了麻烦,这是我第一次使用异步语言进行编程。
我在这里尝试做的基本上是从猫鼬模型“SecSolution”中选择一个随机条目。当前,当返回 arr 时,它是空的,并且在打印顶部的调试之前打印底部的调试消息。我只希望函数在获得其值后返回“arr”。
async function getRandomCardIds(deckIdentifier, cardCount) {
let arr;
switch (deckIdentifier) {
case 102:
await SecSolution.count().exec(async function (err, count) {
let promises = [];
var random = Math.floor(Math.random() * count);
for (let i = 0; i < 2; i++) {
promises.push((await SecSolution.findOne().skip(random).lean())._id);
}
arr = await Promise.all(promises);
debug("This gets printed second" + arr);
});
break;
}
debug("this gets printed first");
return arr;
}
提前致谢!
解决方案
async
使用/时不要使用回调await
。(当使用简单的 Promise 时,只 then
使用回调)。此外,您不应该使用await
仍然需要作为承诺对象的承诺,将其传递给Promise.all
. 你的代码应该是
async function getRandomCardIds(deckIdentifier, cardCount) {
switch (deckIdentifier) {
case 102:
const count = await SecSolution.count(); // a promise(like object)
let promises = [];
var random = Math.floor(Math.random() * count);
for (let i = 0; i < 2; i++) {
promises.push(SecSolution.findOne().skip(random).lean());
}
let arr = await Promise.all(promises);
debug("This gets printed second" + arr);
return [arr[0]._id, arr[1]._id];
break;
}
debug("this gets printed first");
return undefined;
}
除了访问_id
结果数组中对象上的 s 之外,您还可以直接转换承诺(类似于您尝试使用 的await
):
promises.push(SecSolution.findOne().skip(random).lean().then(card => card._id));
推荐阅读
- ruby-on-rails - devise_token_auth 如何访问 user.created_at
- c# - 启动和等待任务有什么区别?
- ibm-midrange - 使用 JT400 获取所有作业的 CPU 利用率
- python - matplotlib 和 PyQt5 的问题
- javascript - 日历禁用带有来自 XSODATA 绑定 SAPUI5 的数据的日期
- angular - Angular 6 ng serve 适用于 Windows 但不适用于 OS X
- python - 如何抓取网页中并排放置的两个表的数据?
- c# - MediaElement 不会播放项目目录之外的文件
- lua - Roblox 传送脚本工作,但随机传送
- protocols - 是否可以使用 Google 的 FlatBuffers 库来实现基于 RTP 的协议?