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)
}
// 回調地獄!
fn1(function(){
fn2(function(){
fn3()
})
})
Promise 解決了回調地獄問題,不會導致難以維護;
合并多個異步請求,節(jié)約時間。
Promise
Promise 是一個對象,對象里存儲一個狀態(tài),這個狀態(tài)是可以隨著內部的執(zhí)行轉化的,為以下三種狀態(tài)之一:等待態(tài)(Pending)、完成態(tài)(Fulfilled)、拒絕態(tài)(Rejected)。
創(chuàng)建 Promise
const myFirstPromise = new Promise((resolve, reject) => {
// ?做一些異步操作,最終會調用下面兩者之一:
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)=>{
成功調用 resolve
失敗調用 reject
})
}
//`then()` 方法返回一個 [`Promise`]。它最多需要有兩個參數:Promise 的成功和失敗情況的回調函數。
fn().then(success,fail).then(success2,fail2)
// promise1和promise2都成功才會調用success1
Promise.all([promise1,promise2]).then(success1,fail1)
// promise1和promise只要有1個成功就會調用success1
//promise1和promise2只要有一個失敗就會調用fail1;
//總之,誰第一個成功或失敗,就認為是race的成功或失敗。
Promise.race([promise1,promise2]).then(success1,fail1)
finally()方法返回一個[Promise]。在promise結束時,無論結果是fulfilled或者是rejected,都會執(zhí)行指定的回調函數。
catch()方法返回一個[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
}
}
```