I'm running the code below. The output I was expecting was:
Start -> End -> While expires -> joke -> setTimeout
However, the output I’m actually getting is:
Start -> End -> While expires -> setTimeout -> joke
Why is this happening?
Shouldn’t "joke" be printed before "setTimeout", since fetch callbacks are stored in the microtask queue, which has higher priority than the task queue where setTimeout callbacks are stored?
console.log("Start");
setTimeout(function cb() {
console.log("setTimeout");
}, 5000);
const apiUrl = "https://api.chucknorris.io/jokes/random";
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
const joke = data.value;
console.log(joke);
})
.catch((error) => {
console.error("Error:", error);
});
console.log("End");
let startDate = new Date().getTime();
let endDate = startDate;
while (endDate < startDate + 10000) {
endDate = new Date().getTime();
}
console.log("While expires");
whileloop. There is no guarantee in which order those two asynchronous callback run. One of the tasks also involving a.then()microtask is a false lead, there is no fixed priority.