await与async

1-1.await

  • awaitWhich means that waiting . It can be followed by an expression. If a value (e.g., strings, numbers, objects, etc. Normal), then the return value is the value itself.
  • However, the most common is followed by an promiseobject. awaitWe will wait for the promisestate by the pendingturn fulfilledor rejected. During this period it will be blocked, delayed the implementation of the latter await sentence statement.
  • If promisethe result is that the object resolve, it will be resolveof value as a awaitcalculation result of the expression.
The nature of syntactic sugar

In fact, awaitand asyncit is itself promiseof syntactic sugar programming. Compare the two usages.

// 异步promise化的函数--模拟请求后端接口
function asyncFn () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (true) {
        console.log('resolve console')
        resolve('resolve return')
      } else {
        reject('reject return')
      }
    }, 2000)
  })
}

// promise
asyncFn().then((res) => {
  console.log(res)
}, (err) => {
  console.log(err)
})

// await
try {
  var res = await asyncFn()
  console.log(res)
} catch(err) {
  console.log(err)
}

// 如果有第二次请求的话,promise需要在then方法继续调用,再用then接受,过多的嵌套依然会增加阅读难度。而await async只需要像写同步代码一样继续书写就可以,它是解决异步编程回调地狱的终极手段。
Example One
// ps:由于js本身现在已经限制了await必须用在async函数中,否则会报错。所以请将下面的复制粘贴到浏览器控制台查看结果

function asyncFn () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (true) {
        console.log('resolve console')
        resolve('resolve return')
      } else {
        reject('reject return')
      }
    }, 2000)
  })
}

var value1 = await asyncFn()
var value2 = await 'plain text'
console.log(value1)
console.log(value2)

//浏览器会依次打印 ‘resolve console’ ‘resolve return’ ‘plain text’
Example Two

If you have questions about the results, you can asyncFn front await removed, and then console in the browser once.

These two compare, you will find the second of resolve consolethe final print out, and the first is the first printing.

Fundamental reason is that the first code awaitblock the execution of the sentence behind, waiting promiseto continue after the end of the statement to determine the result.

Example Three

The former two cases can be imagined, if both of awaitthe latter is followed by promisean object. Then the second await the waiting time is itself waiting for the first time plus awaitwaiting time

function asyncFn1 () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (true) {
        console.log('resolve console1')
        resolve('resolve return1')
      } else {
        reject('reject return1')
      }
    }, 2000)
  })
}

function asyncFn2 () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (true) {
        console.log('resolve console2')
        resolve('resolve return2')
      } else {
        reject('reject return2')
      }
    }, 2000)
  })
}

var value1 = await asyncFn1()
var value2 = await asyncFn2()

// 复制并执行,会发现2s后打印了‘resolve console1’,4s后打印了‘resolve console2’
Think
// 已经知道了await会阻塞代码的执行,如果我们在实际开发中有这样的代码。

function fn () {
  // 假设request是请求后端接口
  var value = await request()
  console.log(value)
  // ...
}
fn()

var arr = []
arr.push('1')
// ...其他不依赖后端接口逻辑

After fn call, due to the awaitobstruction, it is bound to affect the following logic. In the actual development, if the backend interface 5s only response, then the following code will need to wait for 5s. This is obviously unreasonable, in order to solve this phenomenon, we need asynca statement.

1-2.async

Before we know the awaitimplementation of the code will be blocked. The means to solve the drawbacks is that asyncstatement.

async function asyncFn () {
  return 'async'
}
console.log(asyncFn())

Console print, you will find is a print promiseobject. And is Promise.resolvethe object. resolveThe value is asyncFna function of the return value async.

If the function does not return a value, then it is natural to return would be Promise.resolve(undefined).

In fact, the reason why asyncthe statement can solve the awaitblocking problem, because asyncthe statement will be made a function layer of promisepackaging, so that the internal asynchronous operation is actually a pendingconverted resolveor rejectprocesses. This function itself can freely call inside the function awaitwill no longer affect the function of the external code execution.

Guess you like

Origin www.cnblogs.com/jsgoshu/p/11444404.html