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

async function fn(){ //表示异步:这个函数里面有异步任务

let result = await xxx //表示后面结果需要等待

}

读取文件里数据实例:

javascript 复制代码
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();
javascript 复制代码
async function fn(){
            throw new Error('Error出错了');//新建一个错误
        }

        fn().then(res=>{
            console.log(res);
        }, err =>{//别忘了设计错误
            console.log(err);
        })

也可以为catch版

javascript 复制代码
 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函数会中断执行

如:

javascript 复制代码
 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). 最好用此法

javascript 复制代码
try{

		}catch(e){
			
		}

要把涉及网络的代码全包涵在try里以防其中之一出错

javascript 复制代码
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

javascript 复制代码
  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);
        });
相关推荐
恋恋风尘hhh11 小时前
滑动验证码前端安全研究:以顶象(dingxiang-inc)为例
前端·安全
萑澈17 小时前
Windows 7 运行 Electron 安装包报“不是有效的 Win32 应用程序”怎么办
javascript·windows·electron
W.A委员会18 小时前
JS原型链详解
开发语言·javascript·原型模式
懂懂tty18 小时前
React状态更新流程
前端·react.js
小码哥_常18 小时前
告别繁琐!手把手教你封装超实用Android原生Adapter基类
前端
她说彩礼65万18 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
skywalk816319 小时前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
一只蝉nahc19 小时前
vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息
前端·vue.js·unity
状元岐19 小时前
C#反射从入门到精通
java·javascript·算法
子兮曰20 小时前
Bun v1.3.12 深度解析:新特性、性能优化与实战指南
前端·typescript·bun