function fn1(callback) {
setTimeout(()=>{
console.log('fn1')
callback()
}, 1000)
}
function fn2(callback) {
setTimeout(()=>{
console.log('fn2')
callback()
}, 1000)
}
function fn3() {
setTimeout(()=>{
console.log('fn3')
}, 1000)
}
// 回調(diào)地獄!
fn1(function(){
fn2(function(){
fn3()
})
})
Promise 解決了回調(diào)地獄問題,不會(huì)導(dǎo)致難以維護(hù);
合并多個(gè)異步請求,節(jié)約時(shí)間。
Promise
Promise 是一個(gè)對象,對象里存儲(chǔ)一個(gè)狀態(tài),這個(gè)狀態(tài)是可以隨著內(nèi)部的執(zhí)行轉(zhuǎn)化的,為以下三種狀態(tài)之一:等待態(tài)(Pending)、完成態(tài)(Fulfilled)、拒絕態(tài)(Rejected)。
創(chuàng)建 Promise
const myFirstPromise = new Promise((resolve, reject) => {
// ?做一些異步操作,最終會(huì)調(diào)用下面兩者之一:
resolve(someValue); // fulfilled
reject("failure reason"); // rejected
});
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
};
Promise.all 、Promise.race
function fn(){
return new Promise((resolve,reject)=>{
成功調(diào)用 resolve
失敗調(diào)用 reject
})
}
//`then()` 方法返回一個(gè) [`Promise`]。它最多需要有兩個(gè)參數(shù):Promise 的成功和失敗情況的回調(diào)函數(shù)。
fn().then(success,fail).then(success2,fail2)
// promise1和promise2都成功才會(huì)調(diào)用success1
Promise.all([promise1,promise2]).then(success1,fail1)
// promise1和promise只要有1個(gè)成功就會(huì)調(diào)用success1
//promise1和promise2只要有一個(gè)失敗就會(huì)調(diào)用fail1;
//總之,誰第一個(gè)成功或失敗,就認(rèn)為是race的成功或失敗。
Promise.race([promise1,promise2]).then(success1,fail1)
finally()方法返回一個(gè)[Promise]。在promise結(jié)束時(shí),無論結(jié)果是fulfilled或者是rejected,都會(huì)執(zhí)行指定的回調(diào)函數(shù)。
catch()方法返回一個(gè)[Promise],并且處理拒絕的情況。
手寫Promise
class Promise2 {
succeed = null
fail = null
state = 'pending'
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this))
}
resolve(result) {
setTimeout(() => {
this.state = 'fulfilled'
this.succeed(result)
})
}
reject(reason) {
setTimeout(() => {
this.state = 'rejected'
this.fail(reason)
})
}
then(succeed, fail) {
this.succeed = succeed
this.fail = fail
}
}
```