This was orginally posted at lindaojo.com
To fully appreciate the use of Async-Await you must first understand that by default, JavaScript is sync...
For further actions, you may consider blocking this person and/or reporting abuse
The reason
solveC
returnsNaN
is becausegetB
will always returnundefined
.And
1 + undefined
isNaN
.This has nothing to do with the
setTimeout
.And as it happens
Promises
andsetTimeout
are scheduled on separate queues.setTimeout
is scheduled on the task queue while promises are scheduled on the micro-task queue.However promises are often used to get a value from
setTimeout
to a consumerWith async/await one can write
or perhaps
Resources:
I understand, thank you for the detailed correction 💙
Your correction
Simply replaces
c = 1 + undefined
withc = 1 + Promise<pending>
- which similarly doesn't work.The displayed result shows that JavaScript simply concatenated them - with really isn't useful.
Perhaps you meant:
This may be of interest:
No, that was my intention; to show what could go wrong if 'B' was delayed.
Thank you for the resources.
The point is
b
isn't delayed.b
is a promise, not a number.What is delayed is the fulfillment of the promise to a number. In TypeScript this is immediately flagged as an error.
link
This is simply a programming error caused by type confusion
async/await
doesn't "fix" this error.async/await
is simply syntax sugar so you don't have to deal with the promise directly. Butawait
only works on promises - so you have to be aware that you are dealing with promises as it is the case withgetB()
.I'm not advocating the use of TypeScript here but I do think it is essential to "think in types" even when you are using a dynamically typed language.
PS:
await
has its own challenges:Nice and simple introduction. I never had a real-life use case for this, but with this explanation I can think of new ways to implement this. Thanks.
Also, I think (and I may be wrong) that you've made a mistake though.
In the 3rd and 4th code blocks, the async function and the normal function both have the async keyword before them. Is that right?
In the final code block, function getB( ) doesn't have the async keyword, whereas you mention that the await keyword can only be used with async functions.
Thank you, I have fixed the first issue.
Await can only be used "within" an async function. getB() does not have the async keyword because it doesn't use await within it. I hope that's clear.
Thank you so much. This was one of the best explanations.
Thank you 🥰
Great post, it can be quite difficult to wrap your head around promises in JS, and this is a lovely primer.
Didn’t know that it’s possible with just a setTimeout.