关于前端:ES6中的-asyncawait-是什么呢

5次阅读

共计 1061 个字符,预计需要花费 3 分钟才能阅读完成。

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
正文完
 0