So I'm trying to wrap my head about promises/await/async. I can't understand why when go() is executed the alert with "finished" go right after the console.log(coffee). Why does it only wait for getCoffee() and the other axios calls are ran after the "finished" alert when all functions are using await/promises?
function getCoffee() {
return new Promise(resolve => {
setTimeout(() => resolve("☕"), 2000); // it takes 2 seconds to make coffee
});
}
async function go() {
try {
alert("ok");
const coffee = await getCoffee();
console.log(coffee); // ☕
const wes = await axios("https://randomuser.me/api/?results=200");
console.log("wes"); // using string instead of value for brevity
const wordPromise = axios("https://randomuser.me/api/?results=200");
console.log("wordPromise"); // using string instead of value for brevity
alert("finish");
} catch (e) {
console.error(e); // 💩
}
}
go();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
The issue here is that console.log
isn't always as synchronous as one might think. The specification only requires that console.log
display a message in the developer console, but doesn't make any requirements about how or when the message will display. Depending on your browser, results may differ, however usually it's implemented something like the following:
console.log
the request gets pushed onto a console.log
always execute in order)Because console.log
is actually a complex operation like this, it may not finish executing before the alert
statement runs (in some browsers). By replacing every call to alert
with console.log
or every call to console.log
with alert
you should see that things are actually executing in the expected order.
The async/await is working as intended. It is just that the the console takes some time to update or the browser is repainting, therefore the alert
is triggered before it can repaint. You can verify it by using all alert
instead of console.log
. All the alert
are executed in the correct order.As shown in the example below.
function getCoffee() {
return new Promise(resolve => {
setTimeout(() => {resolve("coffee")}, 2000); // it takes 2 seconds to make coffee
});
}
async function go() {
try {
alert("ok");
const coffee = await getCoffee();
alert(coffee); // ☕
const wes = await getCoffee();
alert(wes);
const wordPromise = getCoffee();
alert(wordPromise);
alert("finish");
} catch (e) {
console.error(e); // 💩
}
}
go();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With