You already know that promises enable us to carry out asynchronous transactions. How do you implement in your own programs?
I assume you already know what promises do in Javascript](/promises-javascript) and how event driven programming works :)
Javascript promise is an object. So, Promise should be as easy as using an object. As it is typical in Javascript, everything seems easy, and then stacks up all the different ways to amaze and confuse mortals.
Promise constructor
A bare-bones promise constructor looks like this..
|
|
Here’s the sequence of events -
promiseToLog
initialized. First log statement printed- setTimeOut executed. Timer starts. Promise will only be resolved when timer’s done
- timer running. Moved to next statement to print ‘timer may not be complete…’
- timer running.
promiseToLog
is initialized now. Moved to next statement to print ‘promise initialized’ - timer running. promise resolver or error not called - yet. Moved to next statement to print object. The object says
Promise {<Pending>}
since the promise is not yet resolved - at last timer completes. Call resolver with a message ‘a promise fulfilled..’
- function in
promiseToLog.then()
is executed and the input message ‘a promise fulfilled..’ is printed
Well, that’s about it - you can now claim to be a promising person. Everything else is more sugar.
async - await
Async await is syntactic sugar on top of promises.
Oh.. before you say - yes, I have seen a million posts on the Internet that talk about how async/await blows promises out of water. That is confusing to me to say the least. Why did promise get in the water? Why is async/await pumping air at anything?
Any way, async/await is syntactic sugar for a promise. All the stuff you saw in the previous paragraph - you can in fact “blow the stuff out of the water” and use the newer syntax. The async/ await syntax does not jump around but follows a more traditional approach to the kind of top-down programming we like.
Let us try something more practical this time rather than a timeout. We will fetch a todo
from a server. fetch
returns a promise and we are awaiting
for the promise to resolve before moving to the next statement. await
works only within the context of an async
function.
|
|
The anatomy of async/await
is similar to a promise because it is a promise underneath. However, you can see that we don’t need to write confusing functions everywhere.