最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript詳解使用Promise處理回調(diào)地獄的兩種方法

 更新時(shí)間:2022年11月30日 10:59:04   作者:未及545  
這篇文章主要介紹了JavaScript詳解使用Promise處理回調(diào)地獄的兩種方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一、.then()鏈?zhǔn)秸{(diào)用解決

多層回調(diào)函數(shù)的相互嵌套,就形成了回調(diào)地獄。

缺點(diǎn):

1.代碼耦合性太強(qiáng),難以維護(hù)。

2.大量冗余的代碼相互嵌套,可讀性比較差。

then-fs的基本使用:

調(diào)用then-fs(終端通過npm install then-fs安裝包)提供的readFile()方法,可以異步的讀取文件的內(nèi)容,它的返回值是Promise的實(shí)例對(duì)象,因此可以調(diào)用.then()方法為每個(gè)Promise異步操作指定成功和失敗之后的回調(diào)函數(shù)。

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);
})

但是會(huì)發(fā)現(xiàn)讀取順序是會(huì)變化的。

.then()方法的特性:

如果上一個(gè).then()方法中返回了一個(gè)新的promise實(shí)例對(duì)象,則可以通過下一個(gè).then()繼續(xù)進(jìn)行處理,通過鏈?zhǔn)秸{(diào)用的方法,解決地獄回調(diào)問題。

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()放到最后可以捕獲所有錯(cuò)誤,但是一旦遇到錯(cuò)誤,后面的.then()就不在執(zhí)行。

.catch()放到前面,后面的.then()還可以正常執(zhí)行。

二、async await解決

import thenFs from "then-fs"
 async function getFile(){
// 不加await,打印的r1是一個(gè)promise實(shí)例對(duì)象,加await打印的是結(jié)果
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方法中,第一個(gè)await之前的代碼會(huì)同步執(zhí)行,await之后的代碼會(huì)異步執(zhí)行

import thenFs from "then-fs"
// 在async方法中,第一個(gè)await之前的代碼會(huì)同步執(zhí)行,await之后的代碼會(huì)異步執(zhí)行
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");

到此這篇關(guān)于JavaScript詳解使用Promise處理回調(diào)地獄的兩種方法的文章就介紹到這了,更多相關(guān)JS Promise回調(diào)地獄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

郎溪县| 南和县| 连江县| 西平县| 吉隆县| 泗阳县| 保定市| 双鸭山市| 慈溪市| 江阴市| 雷州市| 英山县| 苏尼特左旗| 闸北区| 宜川县| 宁强县| 湄潭县| 海口市| 秦安县| 双城市| 阳朔县| 榆林市| 宜昌市| 恩平市| 浦县| 万年县| 新绛县| 沐川县| 郁南县| 鹤壁市| 湘潭市| 凤翔县| 芦山县| 南和县| 西平县| 吉木萨尔县| 郑州市| 乐东| 凭祥市| 湾仔区| 防城港市|