About the async/await

  1. Declare an async method
// Declare a function expression const foo = async function(){} // declare a function expression const foo = async function(){}Copy the code
  1. Async return value

Async always returns a Promise object

If the return keyword is not followed by a Promise, the promise.resolve method is called by default for the conversion

async function asyncFunction (){
 return 'Hello World'
}
asyncFunction.then((data)=>{
  console.log(data) // Hello World
})
Copy the code

The asyncFunction above returns a string but uses the then method to get the final value because the string is internally converted to a Promise.

  1. The execution process of async functions
  • Begins the
    • Automatically generate a Promise
  • The execution of
    • Execute immediately exit if a return/throw is encountered
    • Suspends execution if await is encountered, but does not block the main thread until execution resumes after an asynchronous operation following await
  • completed
    • Asynchronous functions return promises whether or not they use await

Best practices

While async can make code look like synchronous code, don’t miss the opportunity for parallelism, as shown in the following example: Wait is asynchronous code, and in actual production can be an interface request, etc.

Bad: The execution completes at least 1000 milliseconds

async function series() { await wait(500); await wait(500); // Wait for the last asynchrony to end and return "done!" ; // Total elapsed time 1000 ms +}Copy the code

Good: At least 500 milliseconds

async function parallel() { const wait1 = wait(500); // execute asynchronous const wait2 = wait(500); // execute asynchronous await wait1; await wait2; return "done!" ; // Total time after all asynchronous acceptance 500 milliseconds +}Copy the code

other

Don’t await for await’s sake, focus on the original code business logic, and take advantage of parallelism. For example, asynchronous code (callback form)

a(() => {
  b();
});

c(() => {
  d();
});
Copy the code

I’m going to use async, if I write


await a();
await b();
await c();
await d();
Copy the code

Use the callback and translate it back

a(() => {
  b(()=>{
    c(()=>{
    	d()
    })
  });
});
Copy the code

Deviate from the original business logic, become serial, continue to optimize async

const asyncA = a()
const asyncC = c()
await asyncA
 b()
await asyncC
 d()
Copy the code

Although a and C are running in parallel, d can execute as soon as C finishes, but if A is slower than C, it becomes

a(()=>{
  d()
})
Copy the code

In other words, the waiting time of D is the maximum of A and C. Continue to optimize Async and finally restore services in the following form

(async () => {
  await a()
  b()
})()

(async () => {
  await c()
  d()
})()
Copy the code

Exception catching is generally possible with a try catch, but the following exceptions are not caught

Async function catchDemo() {try {return, await return Promise. Reject (new Error("Oops!" )); } catch (error) {// code will not be executed here}} catchDemo()Copy the code

Since async runs as a result of returning a Promise, it can be caught with a.catch

catchDemo().catch((error)=>{
  console.log(error)
})
Copy the code

References:

zhuanlan.zhihu.com/p/36521539

www.freecodecamp.org/news/avoidi…