Async Await

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What does the try...catch do?

By using this syntax, not only are we able to handle errors in the same way we do with synchronous code, but we can also catch both synchronous and asynchronous errors. This makes for easier debugging!

An async function will return in one of three ways:

If there's nothing returned from the function, it will return a promise with a resolved value of undefined. If there's a non-promise value returned from the function, it will return a promise resolved to that value. If a promise is returned from the function, it will simply return that promise

async function asyncPromAll() { const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]); for (let i = 0; i<resultArray.length; i++){ console.log(resultArray[i]); } } What does this code do?

In our above example, we await the resolution of a Promise.all(). This Promise.all() was invoked with an argument array containing four promises (returned from required-in functions). Next, we loop through our resultArray, and log each item to the console. The first element in resultArray is the resolved value of the asyncTask1() promise, the second is the value of the asyncTask2() promise, and so on.

async function concurrent() { const firstPromise = firstAsyncThing(); const secondPromise = secondAsyncThing(); console.log(await firstPromise, await secondPromise); } What does this code do?

In our concurrent() function, both promises are constructed without using await. We then await each of their resolutions to print them to the console. With our concurrent() function both promises' asynchronous operations can be run simultaneously. If possible, we want to get started on each asynchronous operation as soon as possible! Within our async functions we should still take advantage of concurrency, the ability to perform asynchronous actions at the same time.

async function fivePromise() { return 5; } fivePromise() .then(resolvedValue => { console.log(resolvedValue); }) // Prints 5 What does this code do?

In the example above, even though we return 5 inside the function body, what's actually returned when we invoke fivePromise() is a promise with a resolved value of 5.

async function noAwait() { let value = myPromise(); console.log(value); } async function yesAwait() { let value = await myPromise(); console.log(value); } noAwait(); // Prints: Promise { <pending> } yesAwait(); // Prints: Yay, I resolved! What does this code do?

In the first async function, noAwait(), we left off the await keyword before myPromise(). In the second, yesAwait(), we included it. The noAwait() function logs Promise { <pending> } to the console. Without the await keyword, the function execution wasn't paused. The console.log() on the following line was executed before the promise had resolved. When used properly in yesAwait(), the variable value was assigned the resolved value of the myPromise() promise, whereas in noAwait(), value was assigned the promise object itself.

But what if our async function contains multiple promises which are not dependent on the results of one another to execute? async function waiting() { const firstValue = await firstAsyncThing(); const secondValue = await secondAsyncThing(); console.log(firstValue, secondValue); } What does this code do?

In the waiting() function, we pause our function until the first promise resolves, then we construct the second promise. Once that resolves, we print both resolved values to the console.

Promise.all() also has the benefit of failing fast. What does that mean?

It means it won't wait for the rest of the asynchronous actions to complete once any one has rejected. As soon as the first promise in the array rejects, the promise returned from Promise.all() will reject with that reason.

Can an await keyword be used anywhere?

No, only in the async functions

Another way to take advantage of concurrency when we have multiple promises which can be executed simultaneously is to await a _______________

Promise.all()

What does the async/await syntax allows us

The async...await syntax allows us to write asynchronous code that reads similarly to traditional synchronous, imperative programs.

async functions always return a promise. What does that mean?

This means we can use traditional promise syntax, like .then() and .catch with our async functions.

What will the single promise of Promise.all() will do?

This promise will resolve when all of the promises in the argument array have resolved. This promise's resolve value will be an array containing the resolved values of each promise from the argument array.

async function asyncAwaitVersion() { let firstValue = await returnsFirstPromise(); console.log(firstValue); let secondValue = await returnsSecondPromise(firstValue); console.log(secondValue); } Let's break down what's happening in our asyncAwaitVersion() function:

We mark our function as async. Inside our function, we create a variable firstValue assigned await returnsFirstPromise(). This means firstValue is assigned the resolved value of the awaited promise. Next, we log firstValue to the console. Then, we create a variable secondValue assigned to await returnsSecondPromise(firstValue). Therefore, secondValue is assigned this promise's resolved value. Finally, we log secondValue to the console.

What is the order of how to write async function?

We wrap our asynchronous logic inside a function prepended with the async keyword. Then, we invoke that function.

async function asyncFuncExample(){ let resolvedValue = await myPromise(); console.log(resolvedValue); } asyncFuncExample(); // Prints: I am resolved now! What does this code do?

Within our async function, asyncFuncExample(), we use await to halt our execution until myPromise() is resolved and assign its resolved value to the variable resolvedValue. Then we log resolvedValue to the console. We're able to handle the logic for a promise in a way that reads like synchronous code.

function nativePromiseVersion() { returnsFirstPromise() .then((firstValue) => { console.log(firstValue); return returnsSecondPromise(firstValue); }) .then((secondValue) => { console.log(secondValue); }); } Let's break down what's happening in the nativePromiseVersion() function:

Within our function we use two functions which return promises: returnsFirstPromise() and returnsSecondPromise(). We invoke returnsFirstPromise() and ensure that the first promise resolved by using .then(). In the callback of our first .then(), we log the resolved value of the first promise, firstValue, and then return returnsSecondPromise(firstValue). We use another .then() to print the second promise's resolved value to the console.

Does async promises always return a promise

Yes

Generally, these async functions are through a

a library, and, in this lesson, we'll be providing them.

With ES6, JavaScript integrated native promises which what?

allows us to write significantly more readable code

We can await the resolution of the promise it returns inside an

async function

function nativePromiseVersion() { returnsFirstPromise() .then((firstValue) => { console.log(firstValue); return returnsSecondPromise(firstValue); }) .then((secondValue) => { console.log(secondValue); }); } Here's how we'd write an async function to accomplish the same thing:

async function asyncAwaitVersion() { let firstValue = await returnsFirstPromise(); console.log(firstValue); let secondValue = await returnsSecondPromise(firstValue); console.log(secondValue); }

In the example below, myPromise() is a function that returns a promise which will resolve to the string "I am resolved now!".

async function asyncFuncExample(){ let resolvedValue = await myPromise(); console.log(resolvedValue); } asyncFuncExample(); // Prints: I am resolved now!

let myPromise = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve('Yay, I resolved!') }, 1000); }); } Now we'll write two async functions which invoke myPromise():

async function noAwait() { let value = myPromise(); console.log(value); } async function yesAwait() { let value = await myPromise(); console.log(value); } noAwait(); // Prints: Promise { <pending> } yesAwait(); // Prints: Yay, I resolved!

Example of native promise's .catch() with an async function

async function usingPromiseCatch() { let resolveValue = await asyncFunction('thing that will fail'); } let rejectedPromise = usingPromiseCatch(); rejectedPromise.catch((rejectValue) => { console.log(rejectValue); })

An example of try...catch

async function usingTryCatch() { try { let resolveValue = await asyncFunction('thing that will fail'); let secondValue = await secondAsyncFunction(resolveValue); } catch (err) { // Catches any errors in the try block console.log(err); } } usingTryCatch();

Given the two versions of the function, the .then() and await async code, which one more closely resembles synchronous code

async...await

By itself, it doesn't do much; async functions are almost always used with the additional keyword _____ inside the function body.

await

Since promises resolve in an indeterminate amount of time,

await halts, or pauses, the execution of our async function until a given promise is resolved.

Example of await

const money = async() =>{ return 5 * 5 } const bigger = async() =>{ const wrongReasons = await money(); if(wrongReasons > 9){ console.log(wrongReasons) } else{ console.log("Nothing to see here") } } bigger()

Example of an async function

const money = async() =>{ return 5 * 5 } const bigger = async(sum) =>{ if(sum > 9){ return "Its bigger than nine " + sum } else{ return "nothing" } } money().then(bigger).then(console.log).catch(console.log)

async function myFunc() { // Function body here }; myFunc(); We'll be using async function declarations throughout this lesson, but we can also create async function expressions:

const myFunc = async () => { // Function body here }; myFunc();

Promise.all() allows us to take advantage of asynchronicity—

each of the four asynchronous tasks can process concurrently.

Example of Await Promise.all()

function Math1(){ return new Promise((resolve,reject)=>{ resolve(10 * 3) }) } function Math2(){ return new Promise((resolve,reject)=>{ resolve(10 * 8) }) } function Math3(){ return new Promise((resolve,reject)=>{ resolve(10 * 10) }) } function Math4(){ return new Promise((resolve,reject)=>{ resolve(10 * 23) }) } const total = async() =>{ const math = await Promise.all([Math1(),Math2(),Math3(),Math4()]); console.log(math[0] + math[1] + math[2] + math[3]) } total();

Example of try...catch statement

function friedChicken(){ const randomChicken = Math.floor(Math.random()*10); return randomChicken * 5 } function hungries(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ const chicken = friedChicken(); if(chicken >= 30){ resolve("Enough chicken " + chicken) } else{ reject("Not enough chicken " + chicken) } },1000) }) } async function chicken(){ try{ let hungry = await hungries(); console.log(hungry) } catch(error){ console.log(error); } } chicken();

Example of Handling Dependent Promises

function friedChicken(){ const randomChicken = Math.floor(Math.random()*10); return randomChicken * 5 } function hungries(mod){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ const chicken = friedChicken(); resolve(chicken * mod) },1000) }) } async function chicken(){ let hungry = await hungries(10); console.log(hungry) } chicken();

Example of Handling Independent Promises

function game(){ return new Promise(resolve=>{ resolve(10) }) } function game2(){ return new Promise(resolve=>{ resolve(20) }) } async function total(){ const gamer = game(); const gamer2 = game2(); console.log(`This game cost atleast ${await gamer} dollars while this one cost ${await gamer2}`); } total();

Example of promise, async, and await

function loyality(sum){ return new Promise((resolve)=>{ setTimeout(()=>{ let number = 0; for(let i = 0; i < sum.length; i++){ number += sum[i] } resolve(number) },1000) }) } async function math(){ const number1 = await loyality([1,2,3,4,5]); console.log(number1) } math()

The async keyword is used to write

functions that handle asynchronous actions.

The true beauty of async...await is when we

have a series of asynchronous actions which depend on one another.

JavaScript is non-blocking: what does that mean?

instead of stopping the execution of code while it waits, JavaScript uses an event-loop which allows it to efficiently execute other tasks while it awaits the completion of these asynchronous actions.

The async...await syntax is syntactic sugar. What does that mean?

it doesn't introduce new functionality into the language, but rather introduces a new syntax for using promises and generators. Both of these were already built in to the language. Despite this, async...await powerfully improves the readability and scalability of our code.

await is an operator:

it returns the resolved value of a promise.

When we pass an array of promises as the argument to Promise.all(), what will it return?

it will return a single promise

We're going to explore this using the following function, which returns a promise that resolves to 'Yay, I resolved!' after a 1 second delay:

let myPromise = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve('Yay, I resolved!') }, 1000); }); }

As it was when working with native promises, Promise.all() is a good choice for what?

multiple asynchronous tasks are all required, but none must wait for any other before executing.

Often in web development, we need to handle asynchronous actions— actions we can wait on while moving on to other tasks. We make requests to what?

networks, databases, or any number of similar operations.

The async...await syntax also makes it easy to store and refer to...

resolved values from promises further back in our chain which is a much more difficult task with native promise syntax.

n most situations, we're dealing with promises that were

returned from functions.

Though using the async...await syntax can save us what?

some typing, the length reduction isn't the main point.

When .catch() is used with a long promise chain...

there is no indication of where in the chain the error was thrown.

Originally, JavaScript used callback functions to handle asynchronous actions. The problem with callbacks is that...

they encourage complexly nested code which quickly becomes difficult to read, debug, and scale.

With async...await, we use _________ statements for error handling.

try...catch

Remember, since async functions return promises...

we can still use native promise's .catch() with an async function

Note: if we have multiple truly independent promises that we would like to execute fully in parallel, what do we need to do?

we must use individual .then() functions and avoid halting our execution with await.

The true beauty of async...await is when we have a series of asynchronous actions which depend on one another. For example, we may make a network request based on a query to a database. In that case,

we would need to wait to make the network request until we had the results from the database.

Remember that await halts the execution of our async function. This allows us to conveniently do what?

write synchronous-style code to handle dependent promises.

With native promise syntax, we use a chain of ________ functions making sure to return correctly each one

.then()


संबंधित स्टडी सेट्स

Chapter 16-Inventory and Operations Management

View Set

2) Harappan Civilization (2600 -1900 BC)

View Set

PSY 202 Week 8 - Chapter 13: Psychological Disorders

View Set

Open Trade practice questions, Currency Exchange Market notes, Balance of Payments Accounts

View Set

Pharmacology Exam 1 - Multiple Choice

View Set

Wong: Chapter 27: The Child with Cardiovascular Dysfunction

View Set

Expansion of The Muslim World unit Quiz study set

View Set