ES6----async/await

简介: ES6----async/await

什么是async/await

async/await 是 ES8(ECMAScript 2017) 引入的新语法,用来简化Promise异步操作。在 async/await 出

现之前,开发者只能通过链式 .then() 的方式处理Promise异步操作。示例代码如下:

import thenFs from 'then-fs'
thenFs.readFile( './1.txt', 'utf-8' ).then(
  result => {
    console.log(result)
    return thenFs.readFile( './2.txt', 'utf-8' )
  }
).then(
  result => {
    console.log(result)
    return thenFs.readFile( './3.txt', 'utf-8' )
  }
).then(
  result => {
    console.log(result)
  }
)

.then 链式调用的优点:解决了回调地狱的问题。

.then链式调用的缺点:代码冗余、阅读性差、不易理解。

async/await的基本使用

使用async/await简化Promise异步操作的实例代码:

import thenFs from 'then-fs'
// 按照顺序读取文件
async function getAllFile() {
  const r1 = await thenFs.readFile( './1.txt', 'utf8' )
  console.log(r1)
  const r2 = await thenFs.readFile( './2.txt', 'utf8' )
  console.log(r2)
  const r3 = await thenFs.readFile( './3.txt', 'utf8' )
  console.log(r3)
}
getAllFile()
11111
22222
3333333

使用async/await,读取文件的返回结果为文件的内容。

async/await的使用注意事项

1.如果在function中使用了await,则 function必须被async修饰。

2.在 async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行。

同步任务全部执行完成后才执行异步任务。

示例:

求输出的顺序

import thenFs from "then-fs"
console.log('A') //同步任务
async function getAllFile() {
  console.log( 'B') //同步任务
  //接下去为异步任务
  //会先退出,执行后面的同步任务
  const r1 = await thenFs.readFile( './1.txt' , 'utf8')
  const r2 = await thenFs.readFile( './2.txt' , 'utf8')
  const r3 = await thenFs.readFile( './3.txt' , 'utf8')
  //异步任务按进入执行队列的顺序输出
  console.log(r1,r2,r3)
  console.log( 'D')
}
getAllFile()
console.log( 'C')//同步任务
A
B
C
11111 22222 3333333
D

相关文章
|
7月前
|
前端开发 JavaScript
|
20天前
|
前端开发 JavaScript
async/await
async/await
16 0
|
1月前
|
API
es6读书笔记(六) async await
es6读书笔记(六) async await
|
3月前
|
前端开发 JavaScript
|
4月前
|
前端开发
ES7 async await return value
ES7 async await return value
|
4月前
|
前端开发
ES6学习(十)—async 函数
ES6学习(十)—async 函数
|
8月前
|
前端开发
|
10月前
|
前端开发 JavaScript
ES8 新特性 ------ async 和 await
ES8 新特性 ------ async 和 await
|
11月前
|
小程序 前端开发
小程序里使用es7的async await语法
小程序里使用es7的async await语法
|
消息中间件 前端开发 JavaScript
ES8 中的 async/await —— 异步函数
ES8 中的 async/await —— 异步函数
150 0