I have trouble understanding the whole concept of async/await and have spent hours reading the documentation and trying to get an example to work. But I still do not understand why this tiny example does not work.
The result I want is for document.body.innerHTML to contain the text "123", since doFirst() should finish running before doSomething() finishes.
But I always get "132", as if I haven’t used async/await at all. What am I doing wrong?
async function doFirst() {
document.body.innerHTML = document.body.innerHTML + "1";
setTimeout(function() {
document.body.innerHTML = document.body.innerHTML + "2";
}, 500);
}
async function doSomething()
{
await doFirst();
document.body.innerHTML = document.body.innerHTML + "3";
}
doSomething();
Sorry for posting this again, last time I posted this question it was marked as a duplicate. So this time I want to clarify that I’m not looking for any answers that show me how to do it properly but also for explanations on why my code does not work.
setTimeoutis callback-based, not Promise-based. You need to convert it to a Promise so you can return it fromdoFirst, so that thedoSomethingcan consume it as a Promise