I have two functions a
and b
that are asynchronous, the former without await
and the later with await
. They both log something to the console and return undefined
. After calling either of the function I log another message and look if the message is written before or after executing the body of the function.
function someMath() {
for (let i = 0; i < 9000000; i++) { Math.sqrt(i**5) }
}
function timeout(n) {
return new Promise(cb => setTimeout(cb, n))
}
// ------------------------------------------------- a (no await)
async function a() {
someMath()
console.log('in a (no await)')
}
// ---------------------------------------------------- b (await)
async function b() {
await timeout(100)
console.log('in b (await)')
}
clear.onclick = console.clear
aButton.onclick = function() {
console.log('clicked on a button')
a()
console.log('after a (no await) call')
}
bButton.onclick = function() {
console.log('clicked on b button')
b()
console.log('after b (await) call')
}
<button id="aButton">test without await (a)</button>
<button id="bButton">test with await (b)</button>
<button id="clear">clear console</button>
If you launch test without await
the function seems to work as if it was synchronous. But with await
, the messages are inverted as the function is executed asynchronously.
So my question is: how javascript execute async
functions when no await
keyword is present?
Real use case: I have an await
keyword which is conditionally executed, and I need to know if the function is executed synchronously or not in order to render my element:
async function initializeComponent(stuff) {
if (stuff === undefined)
stuff = await getStuff()
// initialize
if (/* context has been blocked */)
renderComponent() // render again if stuff had to be loaded
}
initializeComponent()
renderComponent()
P.S: title has the javascript keyword to avoid confusion with same questions in other languages (i.e Using async without await)
bButton.onclick
function into an async function and await forb()
to end in order to get the desired log. – Jose Hermosilla Rodrigoawait
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you. – Ulysse BN