前言
promise是現代web比較常用的一個技術,拜託繁瑣的嵌套回調。讓我們看一些現代瀏覽器的支持度。
canisue 可以查看各個屬性的兼容性。其實各個瀏覽器的支持度都還可以,我下面放出一些可能會出現不兼容情況的polyfill。
補充polyfill
1.promise相關 ,promise.all只能返回全部resolve的,如果有一個reject就會在catch裡返回這個狀態。所以現在有一個需求,能實現無論是否resolve或者reject都能把結果放進返回的數組裡返回。現有 Promise.allSettled() (TC39第4階段草案)。以下是一種polyfill。其實他和all的差距就是在catch的處理上,一個是直接reject。
<code>Promise
.allFinally =function
(args
) {return
new
Promise
(resolve
=> {const
response = [];let
len = args.length;function
setRes
(index, value, response, status
) { response[index] = { status, value }; len--;if
(len ===0
) { resolve(response); } } args.forEach((
item, index
) => {if
(item.constructor ===Promise
) { item.then(res
=> { setRes(index, res, response,"fufilled"
); }, err => { setRes(index, err, response,"rejected"
); }) }else
{ setRes(index, item, response); } }) }) }/<code>
2.Promise.finally 由於有一部分不支持這個方法所以有以下polyfill. finally實際不接受參數,他直接是寫一次then,catch。避免你在寫多餘的東西。
<code>Promise
.prototype.finally =function
(cb
) {return
this
.then(cb).catch(cb); }/<code>
給你代碼|往期回顧:
專欄
給你代碼
29幣
0人已購