In the next video, you’ll learn from Srishti about another way of writing asynchronous code in JavaScript.
Following is the summary of the last video:
1. async & await keywords were introduced in ES8 (ES2017), which are internally based on promises but makes the code even more readable as compared to promises.
2. When the keyword async is prepended to a function, it can be safely assumed that a promise is returned from that function. Even if the function does not explicitly return a promise object, it is made to implicitly return a promise object after resolving it with the value that is returned from the function.
Following is the example code, which you looked at in the video:
Code Snippet:
let foo = async () => Promise.resolve("Srishti"); foo().then(val => alert(val));
Output:
Srishti (inside the alert box)
In the next video, you’ll learn more about the await keyword.
In the last video, you learned that the await keyword makes the code wait until the promise is either resolved or rejected. It is a better way of writing code than using the then() method to handle the success of the promise. Also, note that the await keyword, though waits for the promise to get resolved or rejected, yet does not handle the rejection of the promise. In other words, the await keyword will wait for the promise to get either resolved or rejected. If the promise is resolved, the await keyword will give the result of the promise (if any argument is passed while resolving the promise). However, if an error occurs, you should handle it appropriately since the await keyword will not hold the error(s). For this, you can use the catch block, which is something that you'll learn in the next segment.
An important point to note is that you cannot use the await keyword inside a function which is not declared as an async function. Thus, if you write a normal function (without async keyword prepended to it) like the one given below and try to write the await keyword inside this non-async function,
let foo = () => { // assume namePromise as a promise existing in the code let name = await namePromise; }
then, you get the following error:
Uncaught SyntaxError: await is only valid in async function