javascript - JavaScript节点中的承诺值未更新变量值
问题描述
我有以下代码-
let { user } = req.body;
let name = null;
if (!user) {
getStudent(id).then((x) => {
user = x.user;
name = x.name;
});
}
console.log(user, name); // prints undefined and null
虽然我使用 let 来重新分配值,但似乎这里没有更新。有谁知道为什么?
编辑-我已将 console.log 放入其中,然后根据评论,它已解决。但是我在它下面还有一个需要它的值的异步函数,那我该怎么办?
解决方案
您的回调最终将运行,但仅在您的 console.log 运行之后。你可以用这种方式修复它;
let { user } = req.body;
let name = null;
if (!user) {
getStudent(id).then((x) => {
user = x.user;
name = x.name;
console.log(user, name); // now it will log once the then callback fires.
// put your "one more async function" here inside the then callback.
});
}
另一种方法是使用 async/await 语法来避免嵌套到回调中(也称为“回调地狱”);
if (!user) {
const x = await getStudent(id)
user = x.user;
name = x.name;
}
console.log(user, name);
因为我在这里使用了 await 关键字,所以这段代码需要在一个标记为 async 的函数中。
推荐阅读
- google-cloud-platform - kubectl - 证书管理器 - 未找到凭据
- python - 连接段和标签段中最近的点
- php - 如何将返回数组用户设置为响应 laravel
- ruby-on-rails - Rails 关联字段未保存
- android - 活动内容转换不起作用
- javascript - hsv到rgb颜色转换背后的数学
- docker - Centos 上的准备失败错误
- c - 使用 C、winsock(windows) 在三星 Tizen 推送服务器中推送消息
- google-api - [google-drive-sdk]:我可以将整个文件夹上传到 goolge 驱动器吗?
- csv - 当 Jmeter 的响应数据是 XML 格式时,在输出的 CSV 文件中我们生成的格式是不可读的。如何克服它