1

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?

minsuga
  • 321
  • 3
  • 11
  • 2
    console.log(user, name); runs before your promise resolves. Write it inside your then. – Tushar Shahi Jun 22 '21 at 07:44
  • Because you're updating the `user` and `name` in async function. It will run after the sync code. So `console.log(user, name)` will always print `undefined` and `null`. – DecPK Jun 22 '21 at 07:45
  • Ok, i have one more async function below it that need the values, but since they're undefined, it's failing. So what can I do? – minsuga Jun 22 '21 at 07:47

1 Answers1

1

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.

larsw
  • 36
  • 3