Async/Await (syntactic sugar on top of Promises)

ref – https://www.toptal.com/javascript/asynchronous-javascript-async-await-tutorial

Promises paved the way to one of the coolest improvements in JavaScript. ECMAScript 2017 brought in syntactic sugar on top of Promises in JavaScript in the form of async and await statements.

Async

Declaring a function as async will ensure that it always returns a Promise so you don’t have to worry about that anymore.

The word “async” before a function means one simple thing: a function always returns a promise.

1st example

We can explicitly return a the static function for class Promise:

So, async ensures that the function returns a promise, wraps non-promises in it.

Await

The await operator is used to wait for a Promise.

It can only be used inside an async function.

The await expression causes async function execution to pause until a Promise is fulfilled, that is resolved or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

The syntax:

The keyword await makes JavaScript wait until that promise settles and returns its result.

If there was no await, JS’s single thread will execute the async function, and down the main execution steps turn by turn. So that then end of your program will be executed even when your function is not done.

It won’t work because there is no await…

doubleAfter2Seconds returns Promise object. But since we don’t wait for it to resolve, the returned value is the Promise object. And not th resolved value that we want.


output:

running addAsync
trash.html:79 a: [object Promise]
trash.html:81 b: [object Promise]
trash.html:88 —–here—–
trash.html:89 [object Promise][object Promise]
trash.html:67 doubleAfter2Seconds: 4
trash.html:67 doubleAfter2Seconds: 6

As you can see, when your function is finally done, the result will be stranded. With nothing to execute the returned result.

Using await, it makes the JS thread wait until the promise is returned from the async function. Then proceeds to process it.


output:

running addAsync
trash.html:67 doubleAfter2Seconds: 4
trash.html:79 a: 4
trash.html:67 doubleAfter2Seconds: 6
trash.html:81 b: 6
trash.html:88 —–here—–
trash.html:89 10

In a more simple example:

await literally makes JavaScript wait until the promise settles, and then go on with the result.
That doesn’t cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.
(JS only has 1 thread, which can skip around and execute different tasks, doing a little at a time)


output:
— begin —

Promise {: 3}__proto__:
Promise[[PromiseStatus]]: “resolved”
[[PromiseValue]]: 3

3

If you wish to await two or more promises in parallel, you must still use Promise.all.

Examples of using both

Asynchronous execution
Await is used inside of the async.

When we call a function with async, it

1) returns a Promise object
2) runs asynchronously

You can see this asynchronous activity going on because as the function f runs, the JS execution also continues
down and logs “grandma says:….come to dinner…!!….”.

using await and then at the same time

Whenever we deal with async functions, we must return a Promise. Thus we create a Promise, and make it run a setTimeout
function which is asynchronous. The setTimeout executes code after 3 seconds.

However, in our code, the Promise does not get returned right away due to the “await” statement. Rather, we must wait for the Promise to finish before moving on.
Therefore, the log statements and return Promise MUST wait for the Promise to resolve FIRST.
After the Promise resolves, we return the promise object.

Finally, because the promise object was already resolved, the
then() gets executed right away.

No Await

If we remove the await, the promise gets created, then since there is no “await”, we continue
with the log statements, and then returns the promise object.
Then the Promise executes the setTimeout, and resolves after 3 seconds.
What’s waiting for the resolve will be the then().

The execution will run in this order:

start of f()
create new Promise object
Wait for the Promise to resolve
here….
there….
everywhere…!!….
return the Promise object
waited 3 sec
1ST THEN:oh yea!

Another Example

Another example shows that await actually stops execution on the await line within that async function. While it waits, the JS execution will still move on
to execute after the async functionK

This is shown at 10, where the new Promise object has been created and will be returned. When it returns the Promise object, execution will need wait for the Promise to finish. Since the Promise takes 2 seconds, JS execution will continue after the async func onto line 11.

After the 2 seconds, we resolve the Promise at line 12. Then go on to 13, which we now have the passed in parameter value from the Promise’s resolve.

Whenever you “await” for a Promise, the rest of the async function will not run. Because it is “awaiting” your Promise to finish.
However, it will continue to execute the code that takes place AFTER the async function.

Take note at var x, it is awaiting a Promise to resolve inside of resolveAfter2Seconds…while it is waiting, execution continues at 11.

One more…!