async/await 是什么?


async 函数,就是 Generator 函数的语法糖,它建立在Promises上,并且与所有现有的基于Promise的API兼容。

1、Async — 声明一个异步函数 ( async function someName(){...} )

  • 自动将常规函数转换成Promise,返回值也是一个Promise对象
  • 只有async函数内部的异步操作执行完,才会执行then方法指定的回调函数
  • 异步函数内部可以使用 await

2、Await — 暂停异步的功能执行 ( var result = await someAsyncCall() ) 😉

  • 放置在Promise调用之前,await强制其他代码等待,直到Promise完成并返回结果
  • 只能与Promise一起使用,不适用与回调
  • 只能在async函数内部使用

What are the async and await ?


The async function, it's a syntactic sugar of Geneartor function, it is built on Promise, and is compatible with all existing Promise-based API.

1、The async -- declare a async function ( async function someName(){...} )

  • Automatically convert regular functions to Promise, and the return value is also a Promise object.
  • Only after asynchronous operation inside async function is executed, then execute the callback function specified by then method.
  • we can use await inseide asynchronous function

2、The await -- Paused the asnychronous function execution ( var result = await someAsyncCall() )

  • Placed before the Promise Call, the await forced other codes to wait until the Promise completes and return the result.
  • Can only be used with Promise toghter, it's not suitable for callback
  • Can only be used inside async function

Damiao_Lee
10 声望1 粉丝

my name is damiao.