I'm experiencing an unexpected order of execution when using Promises and async/await in JavaScript. Here’s the code snippet:
let a = "Hanzala" let newPromise = new Promise((resolve, reject) => { let error = false if (!error) { setTimeout(() => { console.log("Async Task"); resolve(a) }, 1000) } else { reject("Error") } }); newPromise .then((data) => { console.log("Async resolved",data) return data.toUpperCase() }) .then((data) => { console.log(data+" from second then") }) .catch((e) => { console.log(e + " Async rejected"); }); (async () => { try { const res = await newPromise console.log(res+ " from async await") } catch (error) { console.log(error+"Error form async"); } })(); The Output is :
Async Task Async resolved Hanzala Hanzala from async await HANZALA from second then Question:
Why does the output order differ from my expectation? Specifically, why does the log "Hanzala from async await" appear before "HANZALA from second then"?
expected Output:
Async Task Async resolved Hanzala HANZALA from second then Hanzala from async await Additional Information:
- I understand that both Promises and async/await use the microtask queue, but I’m unclear on how their execution order is determined in this scenario.
- Any insights into how the event loop handles this would be appreciated.
awaitand.then()chains.async/await. You'd get the same behaviour if you had usednewPromise.then(…)instead ofawait newPromise.