1. The function of the async keyword

Async is the identifier of an asynchronous function, indicating that the function is an asynchronous function and returns a Promise object.

function fn1() {
  return 1
}
console.log(fn1()) //1

async function fn2() {
  return 1
}
console.log(fn2()) // Promise{<fulfilled>:1}
Copy the code

As can be seen from the above example, the return value of async function is a Promise object. Since it is a Promise object, it is natural to use the properties of its prototype, such as then, catch, and so on.

fn2()
.then(r => {
  console.log(r) // 1
})
Copy the code

This is a big pity. Even in fn2, return Error(‘2’) will fall into the then method. Will async return promise state by default?

2. What is await?

Await is an abbreviation of async wait. An expression is to be returned, whether or not a promise is to be returned. Await can only be used in async functions.

function sync() {
  setTimeout(() => {
    return 1
  }, 1000)
}

async function async1(){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(1)
    }, 2000)
  })
}

async function test(){
  await sync() //undefined
  console.log(1)
}

async function test2() {
  await async1()
  console.log(1)
}

test()
test2()
Copy the code

Test2 prints 1 after test and 2 seconds after test2.

As you can see, if await is a promise object, it will “block” the following code until the promise object returns a result, whether it succeeds or fails.

If it’s not apromiseObject then it is a synchronization function that executes synchronously according to JS rules.

If it is not a Promise object, the expression after await is something to wait for

There was a misunderstanding here: I thought ifawaitIf it’s not onepromiseObject then it is a synchronization function that executes the following code directly, which is not the case, if not the casepromiseThe object thenawaitThe rest of this is the same as inthenExecution, withpromiseThe difference is if you are waiting for onepromiseObject, then wait for the object to complete parsing, if notresolveorrejectThen the rest will not be executed. Here are two examples:

// eg1 function fn1() { return new Promise(()=> { }) } async function fn2() { await fn1() console.log('wait fn1') // The value here is never printed, } fn2() // eg2 async function fn2() {await 2 console.log(24) // print} fn2() Async function fn2() {promise.resolve (2).then(r => {console.log(24)})} fn2() console.log('this')Copy the code

Notice that I annotated undefined in the test function because the expression after await will be executed immediately if it is a function, and undefined will be returned immediately after sync and will not wait for the value to be returned after the timing completes

  • aboutawaitThe return value

1. Await is followed by a promise object. If the state is resolve, the value is the resolve parameter. If it is reject, an error is thrown

// resolve let p = await Promise.resolve(3) console.log(p) // 3 // reject let p = await Promise.reject('error') Console. log(p) // Console errorCopy the code

2. Await is not a promise object, the return value is the value itself

let p = await 3
console.log(p) // 3
Copy the code

3. Error capture

A Promise can also be ‘resolve’, ‘reject’. So how do you deal with ‘reject’?

  • usetry catchcapture
function fn() { return Promise.reject('error') } async function asyncFn() { try { await fn() console.log(1) // } catch(e) {console.log(e) // error}}Copy the code

So what we can do is we can put something that might go wrong inside a try and if something goes wrong, the rest of the code after the try doesn’t get executed, it just jumps right into the catch

  • usepromise.catchcapture
function fn() {
   return Promise.reject('error')
}

async function asyncFn() {
    await fn().catch(e => console.log(e))
    // do something
}
Copy the code

4. Application scenarios

In business development, we may encounter, for example, that you need to wait for the completion of interface A request to perform an operation. If you do not use await, you can directly insert the operation into the then chain of the request. Let’s compare the two writing methods.

// do not use await function HTTP () {axios.get('url').then(r => {doIt()}).catch(e => {console.log(e)})} function doIt() {// do something} // use await function HTTP () {return new Promise((resolve, reject) => { axios.get('url') .then(r => { resolve('success') }) .catch(e => { reject('error') }) }) } function doIt() {  // do something } async function fn() { let p = await http() if (p === 'success') { doIt() } else { .... } } fn()Copy the code