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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

未及545   2022-11-30 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们