I apologize if this is a basic question. I am really puzzled by how Promise works in Javascript.
I have the following piece of code:
function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Done waiting");
resolve(ms);
}, ms);
});
}
let a = true;
let p = new Promise(async (resolve, reject) => {
await wait(3000);
console.log("Inside Promise");
if (a) {
resolve("Success");
} else {
reject("Failure");
}
});
const func = async () => {
let output = await p;
console.log(output);
};
func().then(console.log("abc"));
This is the printout:
abc
Done waiting
Inside Promise
Success
I cannot, for the life of me, figure out why abc
is printed first. Shouldn't it wait for func() to finish executing? I expected abc
to be printed last. Can anyone walk me through the steps of execution? Thanks in advance. I would really appreciate it.
What you've provided to Promise.then
is not a callback and it is evaluated immediately at runtime. You need to move the console.log
into the body of the function instead:
func().then(() => console.log("abc"));
See working example below:
function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Done waiting");
resolve(ms);
}, ms);
});
}
let a = true;
let p = new Promise(async (resolve, reject) => {
await wait(3000);
console.log("Inside Promise");
if (a) {
resolve("Success");
} else {
reject("Failure");
}
});
const func = async () => {
let output = await p;
console.log(output);
};
func().then(() => console.log("abc"));