asynchronous Flashcards
async
The async keyword is used to write functions that handle asynchronous actions. We wrap our asynchronous logic inside a function prepended with the async keyword. Then, we invoke that function.
What does async return?
async functions always return a promise. This means we can use traditional promise syntax, like .then() and .catch with our async functions. 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
How to write an async function?
async function withAsync(num) { if (num === 0) { return 'zero'; } else { return 'not zero'; }
}
The await Operator
The await keyword can only be used inside an async function. await is an operator: it returns the resolved value of a promise. 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.
How to write an async function with an await operator?
const shopForBeans = require(‘./library.js’);
async function getBeans() { console.log(`1. Heading to the store to buy beans...`); let value = await shopForBeans(); console.log(`3. Great! I'm making ${value} beans for dinner tonight!`); }
getBeans();
What are dependent promises?
Promises that are chained together where each succeeding promises relies on the previous promise
How to write an async function with dependent promises?
async function asyncAwaitVersion() {
let firstValue = await returnsFirstPromise();
console.log(firstValue);
let secondValue = await returnsSecondPromise(firstValue);
console.log(secondValue);
}
How do you handle errors with an async function?
With async…await, we use try…catch statements for error handling. 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!
How do you write a catch and try async function?
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();
How do you handle multiple promises in one function that do not depend on one another to take advantage of concurrency?
async function concurrent() { const firstPromise = firstAsyncThing(); const secondPromise = secondAsyncThing(); console.log(await firstPromise, await secondPromise); }
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.
What is Promise.all()?
Another way to take advantage of concurrency when we have multiple promises which can be executed simultaneously is to await a Promise.all().
We can pass an array of promises as the argument to Promise.all(), and it will return a single promise. 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.
What is the syntax for using a Promise.all()?
async function asyncPromAll() { const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]); for (let i = 0; i
When is Promise.all() a good choice?
As it was when working with native promises, Promise.all() is a good choice if multiple asynchronous tasks are all required, but none must wait for any other before executing.
Promise.all() also has the benefit of failing fast, meaning 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