欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > ES6入门---第三单元 模块三:async、await

ES6入门---第三单元 模块三:async、await

2025/5/6 9:22:43 来源:https://blog.csdn.net/qq_41775119/article/details/81814781  浏览:    关键词: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);});


      

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词