JavaScript詳解使用Promise處理回調(diào)地獄的兩種方法
一、.then()鏈?zhǔn)秸{(diào)用解決
多層回調(diào)函數(shù)的相互嵌套,就形成了回調(diào)地獄。
缺點:
1.代碼耦合性太強,難以維護。
2.大量冗余的代碼相互嵌套,可讀性比較差。
then-fs的基本使用:
調(diào)用then-fs(終端通過npm install then-fs安裝包)提供的readFile()方法,可以異步的讀取文件的內(nèi)容,它的返回值是Promise的實例對象,因此可以調(diào)用.then()方法為每個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);
})
但是會發(fā)現(xiàn)讀取順序是會變化的。
.then()方法的特性:
如果上一個.then()方法中返回了一個新的promise實例對象,則可以通過下一個.then()繼續(xù)進行處理,通過鏈?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()放到最后可以捕獲所有錯誤,但是一旦遇到錯誤,后面的.then()就不在執(zhí)行。
.catch()放到前面,后面的.then()還可以正常執(zhí)行。
二、async await解決
import thenFs from "then-fs"
async function getFile(){
// 不加await,打印的r1是一個promise實例對象,加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方法中,第一個await之前的代碼會同步執(zhí)行,await之后的代碼會異步執(zhí)行
import thenFs from "then-fs"
// 在async方法中,第一個await之前的代碼會同步執(zhí)行,await之后的代碼會異步執(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript+html5 canvas制作色彩斑斕的正方形效果
這篇文章主要介紹了JavaScript+html5 canvas制作色彩斑斕的正方形效果,實例分析了JavaScript結(jié)合html5 canvas實現(xiàn)圖形動態(tài)繪制的技巧,需要的朋友可以參考下2016-01-01
JavaScript實現(xiàn)枚舉的幾種方法總結(jié)
在前端開發(fā)中,我們可能經(jīng)常需要用到枚舉,使用枚舉的好處是為了讓代碼的可讀性更強,避免直接使用數(shù)字或未知的字符串,但是在JavaScript中,要自己實現(xiàn)一個枚舉功能,那么大家能想到多少種實現(xiàn)枚舉的方法呢,我將介紹幾種實現(xiàn)枚舉的好方法2023-08-08
詳解JavaScript實現(xiàn)繼承的五種經(jīng)典方式(附圖解)
JavaScript中的繼承是一種機制,通過它可以創(chuàng)建一個對象,該對象可以享有另一個對象的屬性和方法,本文將詳細(xì)的為大家介紹實現(xiàn)繼承的五種經(jīng)典方式,感興趣的小伙伴跟著小編一起來看看吧2023-08-08

