This Thursday, departmental sharing. A colleague demonstrated using Node.js to create a crawler that calls each other’s interfaces to crawl data. If a large number of asynchronous requests are made through Node.js, the server of the other party will crash and fail to respond. Therefore, colleagues transform the code into synchronous mode through async/await, and request the other interface in sequence one by one to get data. Therefore, the keywords async and await are studied.

What are async and await

async

Async is used to modify functions. It is used to turn a function into an asynchronous function that returns a Promise.

Functions decorated with async have a return value

If the async decorated function has a return value, the return value is returned as an argument to promise.resolve (value). It may be hard to understand, but look at the following example:

async function test() {return "Return value in case of return"} / / executiontest() returns a Promisetest().then((value)=>{console.log(valuetestfunctionreturnThe value of the})Copy the code

The console output is the return value if there is a return

Async – decorated functions have no return value

If async modifiers do not have a return value, then the value in promise.resolve (value) returns undefined, as in the following example:

async function test(){
}

test().then((value)=>{console.log(value) // here promise.resolve argument, becausetestFunction is notreturnValue, so undefined})Copy the code

The console output is undefined

await

Await literally means to wait. It is used to wait for an asynchronous function to finish executing. Await blocks the execution of the thread, so when await is used, it must be done in an asynchronous function decorated with async.

To prefix an ordinary function call with await

To await a call to an ordinary function, it will immediately return the return value of the ordinary function, as shown in the following example:

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a return value -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();
  console.log(hi);
}

test() / / console output: hi, world -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- there is no return value -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -function sayHi(){
  var hi= "hi,world";
}

async function test(){
  const hi=await sayHi();
  console.log(hi);
}

test// Console output :undefinedCopy the code

We can see that in async function, adding await before the call of ordinary function will return the return value of ordinary function, if the ordinary function has no return value after execution, return undefined.

To await a function decorated with async before it executes

Resolve (value); resolve(value); resolve(value); resolve(value); The return value in async functions. Look at the following example:

async function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();
  console.log(hi);
}

test(a)Copy the code

Console output :hi,world.

Use await before a Promise object

Use “await” before a Promise. We know async returns a Promise, so why are we talking about “await” again?

We are not specifying the then() method of the async Promise object. We are adding await modifier to the Promise object to help us understand more about the Promise object. What is the return value of await? Taking a look at the following example, let’s guess what the console output will look like.

async function test(){
  const hi=await new Promise(function(resolve,reject){
    resolve("hi,world")
  }).then((value)=>{
    return "hello,world"
  });
  console.log(hi);
}

test(a)Copy the code

The output of this code in the console is hello,world.

WTF!!!!! ? Resolve (value) returns the value of promise.resolve (value).

Guest officer calm down, calm down.

Since async only returns a Promise object and does not specify promise.then (), and decorates async calls with await, await helps us add promise.then (), And changing the state of Promise from Pending= “resolved,” hi equals myHi:

 async function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();

  const myHi=await new Promise((resolve,reject)=>{
    resolve("hi,world")
  }).then((value)=>{
    returnvalue; }) console.log(hi); // Output: hi,world console.log(myHi)test(a)Copy the code

So when I say await async, I say the value returned is the value in promise.resolve (value).

If the async modifier does not return a value, then the value is undefined and the return value of the await modifier is undefined. I’m not going to show you that, but you can try it out for yourself.

Take a look at the following code:

async function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();

  const myHi=await new Promise((resolve,reject)=>{
    resolve("hi,world")
  }).then((value)=>{
    return "hello,world"; / / modifyreturn "hello,world"}) console.log(hi); // Output :hi,world console.log(myHi) // output :hello,world}test(a)Copy the code

Resolve (value) returns hello,world instead of value, and the value of await is hello,world.

Return the return value of the last promise.then () if a Promise has more than one promise.then () method. If no value is returned, undefined is returned. Take a look at this code:

async function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();

  const myHi=await new Promise((resolve,reject)=>{
    resolve("hi,world")
  }).then((value)=>{
    return "hello,world";
  }).then((value)=>{
    return "Hi, barley"}) console.log(hi); // Output :hi,world console.log(myHi) // Output :hi, barley}test(a)Copy the code

If our Promise state is from Pending = “Rejected”, what is the return value of await?

async function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();

  const myHi=await new Promise((resolve,reject)=>{
    reject("error")
  }).then((value)=>{
    return "hello,world";
  },(error)=>{
    returnvalue }) console.log(hi); Console. log(myHi) : error}test(a)Copy the code

As we can see, the return value of the class is promise.reject (value). If there is no return value, the return value of await is undefined.

However, we often use Promise objects without specifying the proise.reject callback. Such as:

async function sayHi() {return "hi,world";
}

async function test(){
  const hi=await sayHi();

  const myHi=await new Promise((resolve,reject)=>{
    reject("error")
  }).then((value)=>{
    return "hello,world"; }) // Console. log(hi) does not specify promise.reject; console.log(myHi) }test(a)Copy the code

Uncaught Exception: error So to avoid this, we should put await await promises in try{}.catch(). Such as:

async function sayHi() {return "hi,world";
}

async function test(){ const hi=await sayHi(); {var myHi=await new Promise((resolve,reject)=>{var myHi=await new Promise(resolve,reject)=>{"error")
    }).then((value)=>{
      return "hello,world"; }) }catch(e) { myHi=e; } console.log(hi); Console. log(myHi) : error}test(a)Copy the code

Async and await are in full swing

The benefits of async and await come when promises require multiple calls to promise.then ().

function add(num){
  return num+200;
}

async function test(){

  const step1=await add(100);
  const step2=await add(step1);
  const step3=await add(step2);
  console.log(step3)
}

function thenTest(){
  const result=new Promise( (resolve,reject)=> {
    resolve(100)
  }).then((value)=>{
    return add(value)
  }).then((value)=>{
    return add(value)
  }).then((value)=>{
    console.log(add(value))
  })

}

test// Output: 700 (100+200+200+200)thenTest() // Output: 700 (100+200+200+200)Copy the code

We can see that async and await avoid multiple calls of Promise’s then() function, making the syntax clearer.

I am Damai, if you like my article, please give me a careful heart.