首页 > 解决方案 > 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 放入其中,然后根据评论,它已解决。但是我在它下面还有一个需要它的值的异步函数,那我该怎么办?

标签: javascriptnode.jsexpress

解决方案


您的回调最终将运行,但仅在您的 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 的函数中。


推荐阅读