Async & Await
Lesson 9 of 9 in Coddy's Tricky parts of Modern Javascript (ES6+) course.
If you have completed the last lesson, you must be thinking that promises are hard to understand or even hard to remember its syntax !
Don't worry ! ES6 is here to help you out on this.
<i>async</i>and<i>await</i>make promises easier to write
consider a function which performs an asynchronous (time consuming) task.
We want this function to return promise and also wait for the result of the promise.
if we write
asyncbefore any Javascript function , it always returns a promise.await will make the function to wait for a promise and pause the function execution until the promise is resolved.
consider an example of fetching data from a server , it may take few seconds
async function fetchData () {
const response = await fetch("/url"); // wait for the promise
const movies = await response.json(); // wait for the promise
return movies;
}
fetchData.then(val => console.log(val)) // the returned data from APIThe
awaitkeyword can only be used inside anasyncfunction.
async-await can be used in both normal and arrow functions.
const someFunc = async (a) => { await //code }Challenge
MediumYou are given a function foo, which gets an integer n and returns a promise.
Write a function sum which gets two promises as input and returns the sum of their resolved results.
The function should be marked with async!
Try it yourself
const foo = async (x) => {
return x
}
// Write your code belowAll lessons in Tricky parts of Modern Javascript (ES6+)
2Let's dive in
Block scope - let & constThe Arrow FunctionsSpread and Restfor - of loopClassesPromisesAsync & Await