I’m trying to figure out how the code precedence and order is with presence of await
, but it seems a little bit confusing, for instance I have code below:
const a = Promise.resolve(98);
const b = Promise.resolve(78);
const c = Promise.resolve(45);
const e = Promise.resolve(23);
setTimeout(() => console.log("hi8"));
const d = c.then(() => {
console.log("hi9")
});
console.log("hi0");
async function lome() {
console.log("hi1");
await setTimeout(() => console.log("hi7"));
console.log("hi2");
}
lome2();
lome();
console.log("hi3");
async function lome2() {
console.log("hi10");
await e.then(() => {
console.log("hi11")
});
console.log("hi12");
}
setTimeout(() => console.log("hi4"));
b.then(() => console.log("hi6"));
//output:hi0
//hi10
//hi1
//hi3
//hi9
//hi11
//hi7
//hi6
//hi12
//hi2
//hi8
//hi4
so based on this code, we have sync codes, then promise handlers, and after that the code after await, then setTimeouts. so I said maybe the code after await
has a precedence higher than setTimeout
s and lower than promise handlers
, then I confronted an issue in second example(check the code below):
const a = Promise.resolve(98);
const b = Promise.resolve(78);
const c = Promise.resolve(45);
const e = Promise.resolve(23);
setTimeout(() => console.log("hi8"));
const d = c.then(() => {
console.log("hi9")
});
console.log("hi0");
async function lome() {
console.log("hi1");
await setTimeout(() => console.log("hi7"));
console.log("hi2");
}
lome2();
lome();
async function lome2() {
console.log("hi10");
await e.then(() => {
console.log("hi11")
});
console.log("hi12");
}
setTimeout(() => console.log("hi4"));
b.then(() => console.log("hi6"));
console.log("hi3");
//output:hi0
//hi10
//hi1
//hi3
//hi9
//hi11
//hi2
//hi6
//hi12
//hi8
//hi7
//hi4
in the second example first we have sync code, then we have promise handler in variable d then promise handler in function lome2
, then instead of displaying promise handler result, stored in variable f
which is hi6
, first console displays hi2
which is code after await
in function lome
, so if code after awaits are supposed to have a lower precedence than promise handlers, so why in second example, it got displayed earlier than the last promise handler result?
so, I am confused right now and I’m wondering how code execution precedence is with presence of await
and promise handlers
and setTimeout
s?
p.n: the code is just a dummy code for practicing, don’t peak on its application pls:)
2