How does a return in setTimeout() work?

I remember in the lecture, Mosh was talking about how the return value of a function with its return in setTimeout would be updated after the value was eventually returned.

I am not seeing that, however, when I write my own code:

function asyncBoilWater() {
	setTimeout(() => {
		return ("Water is boiled.")
	}, 3000);
}
let isWaterBoiled = "whatever";
isWaterBoiled = asyncBoilWater();
console.log(isWaterBoiled);
setTimeout(() => console.log(isWaterBoiled), 5000);

I am getting undefined and then another undefined. Did I misunderstand him?

You need to wrap it in a new Promise like

function asyncBoilWater() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Water is boiled.")
    }, 3000);
  })
}

let isWaterBoiled = "whatever";
isWaterBoiled = asyncBoilWater();
console.log(isWaterBoiled);
setTimeout(() => console.log(isWaterBoiled), 5000);

Then you should get “pending” as your first log and “Water is boiled.” as your second.

1 Like