ES6入门---第三单元 模块三:async、await
async function fn(){ //表示异步:这个函数里面有异步任务
let result = await xxx //表示后面结果需要等待
}
读取文件里数据实例:
const fs = require('fs');//简单封装 fs封装成一个promise
const readFile = function (fileName){return new Promise((resolve, reject) =>{fs.readFile(fileName, (err, data) =>{if(err) reject(err);resolve(data);});});
}//async
async function fn(){let f1 = await readFile('data/a.txt');console.log(f1.toString());let f2 = await readFile('data/b.txt');console.log(f2.toString());let f3 = await readFile('data/c.txt');console.log(f3.toString());}
fn();
async function fn(){throw new Error('Error出错了');//新建一个错误}fn().then(res=>{console.log(res);}, err =>{//别忘了设计错误console.log(err);})
也可以为catch版
fn().then(res=>{console.log(res);}).catch(err=>{console.log(err);})
async特点:
1. await只能放到async函数中
2. 相比genrator语义化更强
3. await后面可以是promise对象,也可以数字、字符串、布尔
4. async函数返回是一个promise对象
5. 只要await语句后面Promise状态变成 reject, 那么执行完reject后整个async函数会中断执行如:
async function fn(){await Promise.reject('出现问题了');let a = await Promise.resolve('success');console.log(a);}fn().then(res=>{console.log(res);}).catch(err=>{console.log(err);})
如何解决async函数中抛出错误,影响后续代码:
a). 最好用此法
try{}catch(e){}
要把涉及网络的代码全包涵在try里以防其中之一出错
try{let f1 = await readFile('data/a.txt');let f3 = await readFile('data/c.txt');let f2 = await readFile('data/b.txt');}catch(e){}
b). promise本身catch
async function fn(){await Promise.reject('出现问题了').catch(err=>{console.log(err);});let a = await Promise.resolve('success');console.log(a);}fn().then(res=>{console.log(res);});