promise的缺點之一就是沒法讓promise中斷ajax
Promise.resolve().then(() => { console.log('then 1') }).then(() => { console.log('then 2') }).then(() => { console.log('then 3') }).catch((err) => { console.log(err) })
如上代碼如何讓promise的鏈式調用中斷?promise
Promise.resolve().then(() => { console.log('then 1') throw new Error('xxx') }).then(() => { console.log('then 2') }).then(() => { console.log('then 3') }).catch((err) => { console.log(err) })
Promise.resolve().then(() => { console.log('then 1') return new Promise(() => {}) }).then(() => { console.log('then 2') }).then(() => { console.log('then 3') }).catch((err) => { console.log(err) })
假設咱們要用promsie本身封裝一個ajax, 設置超時中斷時間,若是沒返回就不用返回了, 返回也不作處理了,不重要(雖然和上面的原理不要緊,但不重要,上面是一個promsie的鏈式調用中斷,此例是實際應用中的問題,你管我用幾個promsie呢, 想到了記錄一下)code
function wrap(p1) { let abort let p2 = new Promise((resolve, reject) => { abort = reject }) let p = Promise.race([p1, p2]) // 將延時promise的reject方法掛在到p1與p2的race後的promise上, 能夠在方法外經過調用p的cancel方法,來觸發p2的reject p.cancel = abort return p } let fn = wrap(new Promise((resolve, reject) => { // 假設1秒後ajax返回, 調用resolve setTimeout(() => { resolve() }, 1000) })) fn.then(() => { console.log('ok') }).catch(() => { console.log('err') }) // 設置延時時間500ms, 若是500ms數據買回來,就中斷 setTimeout(() => { fn.cancel() }, 500)