Variable value not getting updated by promise value in JavaScript node

Issue

I have the following code-

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

Though I’m using let that will reassign the values, seems it’s not getting updated here. Anyone knows why?

Edit- i have put console.log inside then as per comments , it’s resolved. But i have one more async function below it that needs it’s value, so what can I do?

Solution

Your callback will eventually run, but only after your console.log has. You could fix it in this manner;

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.
  });
}

An alternative is to use async/await syntax to avoid nesting into callbacks (also called "callback hell");

    if (!user) {
      const x = await getStudent(id)
      user = x.user;
      name = x.name;
    }
   console.log(user, name);

Since I’m using the await keyword here, this code needs to be inside a function labeled async.

Answered By – larsw

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published