一、.then()链式调用解决
多层回调函数的相互嵌套,就形成了回调地狱。
缺点:
1.代码耦合性太强,难以维护。
2.大量冗余的代码相互嵌套,可读性比较差。
then-fs的基本使用:
调用then-fs(终端通过 npm install then-fs 安装包)提供的readFile()方法,可以异步的读取文件的内容,它的返回值是Promise的实例对象,因此可以调用.then()方法为每个Promise异步操作指定成功和失败之后的回调函数。
import thenFs from "then-fs"
thenFs.readFile("./fis/1.txt","utf8").then(r1=>{
console.log(r1);
})
thenFs.readFile("./fis/2.txt","utf8").then(r2=>{
console.log(r2);
})
thenFs.readFile("./fis/3.txt","utf8").then(r3=>{
console.log(r3);
})
但是会发现读取顺序是会变化的。
.then()方法的特性:
如果上一个.then()方法中返回了一个新的promise实例对象,则可以通过下一个.then()继续进行处理,通过链式调用的方法,解决地狱回调问题。
import thenFs from "then-fs"
thenFs.readFile("./fis/1.txt","utf8").then(r1=>{
console.log(r1);
return thenFs.readFile("./fis/2.txt","utf8")
}).then(r2=>{
console.log(r2);
return thenFs.readFile("./fis/3.txt","utf8")
}).then(r3=>{
console.log(r3);
})
.catch()方法
import thenFs from "then-fs"
thenFs.readFile("./fis/11.txt","utf8").catch(err=>{
console.log(err.message);
}).then(r1=>{
console.log(r1);
return thenFs.readFile("./fis/2.txt","utf8")
}).then(r2=>{
console.log(r2);
return thenFs.readFile("./fis/3.txt","utf8")
}).then(r3=>{
console.log(r3);
})
.catch()放到最后可以捕获所有错误,但是一旦遇到错误,后面的.then()就不在执行。
.catch()放到前面,后面的.then() 还可以正常执行。
二、async await解决
import thenFs from "then-fs"
async function getFile(){
// 不加await,打印的r1是一个promise实例对象,加await打印的是结果
const r1=await thenFs.readFile("./fis/1.txt","utf8")
console.log(r1);
const r2=await thenFs.readFile("./fis/2.txt","utf8")
console.log(r2);
const r3=await thenFs.readFile("./fis/3.txt","utf8")
console.log(r3);
}
getFile()
注意:
在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行
import thenFs from "then-fs"
// 在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行
console.log("a");
async function getFile(){
console.log("b");
const r1=await thenFs.readFile("./fis/1.txt","utf8")
console.log(r1);
const r2=await thenFs.readFile("./fis/2.txt","utf8")
console.log(r2);
const r3=await thenFs.readFile("./fis/3.txt","utf8")
console.log(r3);
console.log("d");
}
getFile()
console.log("c");