Usage and understanding of asynchronous and waiting in JavaScript

  • 2021-09-20 19:30:09
  • OfStack

Yesterday's update was "Detailed Explanation of Promise in JavaScript", which actually means the basic usage and my understanding of Promise. There may be mistakes, and you are welcome to point out them. Today, let's talk about "the usage and understanding of async/await in JavaScript"

Usage and Understanding of Asynchronous/Waiting in JavaScript

Any one keyword in a programming language is meaningful, so let's understand it literally first.

1.async

async is the abbreviation of "asynchronous". The function with async keyword declares asynchronous function, and the return value is promise object. If async keyword function does not return promise, it will be automatically wrapped with Promise. resolve ().


async function test() {
 return 'hello word'
}
test();

Running the above code returns the following result

2.await

await can be considered short for async wait. So it should be well understood that async is used to declare that an function is asynchronous, and await is used to wait for an asynchronous method to finish execution.

If it is not waiting for an Promise object, the result of the await expression is what it is waiting for.

If it waits for an Promise object, await gets busy, blocking the following code, waiting for the Promise object resolve, and then getting the value of resolve as the result of the await expression.

Let's look at the following code


function test() {
 return new Promise(resolve => {
  setTimeout(() => resolve("hello word"), 2000);
 });
}

const result = test();
console.log(result.then((val)=>{console.log(val)}));
console.log(' End ')

Let's take the editor editor code execution order as an example,

1. First we define a method that returns an Promise object, and the. then () function returns call success two seconds later.

2. Next, instantiate the test () function.

3. Call the then () function of the result object and receive the return value. Note that this is asynchronous

4. End of printing log

We run the code and see the results

See print "end" first, then print "hello word", this is asynchronous, let's transform the code


function test() {
 return new Promise(resolve => {
  setTimeout(() => resolve("hello word"), 2000);
 });
}

const result = await test();
console.log(result);
console.log(' End ')

Use the await keyword to connect with the test () function to see the return result this time

We found that "hello word" was printed before "End", and console. log ('End') waited two seconds to execute due to the blocking caused by test ().

Let's talk about the advantages and disadvantages again

Advantages: Compared with promise, async/await handles the call chain of then, and the code is much clearer, almost like synchronous code 1.

Disadvantages: Misuse of await can cause performance problems because await blocks code.

Summarize


Related articles: