ES6中的 async/await 是什么呢?
文章目录
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 aPromiseobject. - Only after asynchronous operation inside
asyncfunction is executed, then execute the callback function specified bythenmethod. - we can use
awaitinseide asynchronous function
2、The await -- Paused the asnychronous function execution ( var result = await someAsyncCall() )
- Placed before the
PromiseCall, theawaitforced other codes to wait until thePromisecompletes and return the result. - Can only be used with
Promisetoghter, it's not suitable for callback - Can only be used inside
asyncfunction

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论