Till now we have learnt how to create and consume promises. But the syntax to consume promises can still be very confusing. Therefore in ES8/ES2017, async/await was introduced to Javascript.
Async/Await was designed just to consume Promises. If you want to create Promises we need to jump to our previous technique.
We will consume the below promises using the below previous code.
We can see that there are 3 promise in the above code. Its time to consume the promises now.
We will be creating a async function, which simply means that it is a asynchronous function which will keep on running in the background.
Let’s consume our first promise.
numbers in line 158 is our 1st promise. The await expression will stop the code from executing until promise is fulfilled. If the promise is resolved then the value of the promise is assigned to the Ids on LHS. Let’s have a look.
Let’s consume our pending 2 promises.
Please keep in mind that await keyword can only be used inside the async function.
Let’s try something new. Now let’s try to return a value from this async function.
We get a message that our promise is pending. This is because when the promise is running in the background our focus has shifted to line number 168. Therefore, we cannot achieve this scenario using this approach.
How to solve this ?
An async function always returns a Promise. So if we return a value from the async function using the return keyword as we did, then the promise will automatically be resolved with the returned value. Let’s do this.
We can simply use then() method here as getNumbers() method in line 167 already returns a promise which is resolved.
Therefore it is better to use async/await while consuming the promises as it looks like a synchronous code, however behaves in a asynchronous way.