JavaScript详解使用Promise处理回调地狱的两种方法

这篇文章主要介绍了JavaScript详解使用Promise处理回调地狱的两种方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

一、.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");

到此这篇关于JavaScript详解使用Promise处理回调地狱的两种方法的文章就介绍到这了,更多相关JS Promise回调地狱内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是JavaScript详解使用Promise处理回调地狱的两种方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程