Promise原始碼深入理解

2022-09-07 12:27:09 字數 2479 閱讀 8439

// promise的第一版實現

function

mypromise(constructor)

}function

reject(reason)

}//捕獲構造異常

try catch (e)

}mypromise.prototype.then = function (onfullfilled, onrejected)

}var

p = new

mypromise(function (resolve, reject) );

p.then(function (x) ) //輸出1

// mypromise 無法執行非同步的resolve

varp = new

mypromise(function (resolve, reject) , 1000)

});p.then(function (x) ) //無輸出

// 2, 基於觀察者

function

mypromise(constructor) );}}

function

reject(reason) )}}

//捕獲構造異常

try catch (e)

}mypromise.prototype.then = function (onfullfilled, onrejected) );

self.onrejectedarray.push(function () );

break;

case

"resolved":

onfullfilled(self.value);

break;

case

"rejected":

onrejected(self.reason);

break; default:}}

varp = new

mypromise(function (resolve, reject) , 1000)

});p.then(function (x) ) //無輸出

// 3.v3.0then方法實現鏈式呼叫

mypromise.prototype.then = function (onfullfilled, onrejected)

catch (e)

});self.onrejectedarray.push(function () catch (e)

});})

break;

case

"resolved":

promise2 = new

mypromise(function (resolve, reject) catch (e)

})break;

case

"rejected":

promise2 = new

mypromise(function (resolve, reject) catch (e)

})break;

default:

}return

promise2;

}var

p = new

mypromise(function (resolve, reject) , 1000)

});p.then(function (x) ) //輸出 1 鏈式呼叫1 鏈式呼叫2

// 4.v4.0 then函式中的onfullfilled和onrejected方法的返回值問題

function

resolvepromise(promise, x, resolve, reject)

letisused;

if (x !== null && (typeof

x === "object" || typeof

x === "function")) , function (e) )

} else

} catch (e)

} else

}mypromise.prototype.then = function (onfullfilled, onrejected) catch (e)

})});

self.onrejectedarray.push(function () catch (e)

})});

})case

"resolved":

promise2 = new

mypromise(function (resolve, reject) catch (e)

})})

break;

case

"rejected":

promise2 = new

mypromise(function (resolve, reject) catch (e)

})})

break;

default:

}return

promise2;

}

深入理解Promise

最近把promise重新學了一下,對promise有了更深層次的理解,話不多說,可以看下 自定義promise函式模組 function window onrejected 0 function resolve value catch error 向後傳遞失敗的reason const self t...

Okhttp深入理解及原始碼解析

okhttpclient okhttpclient new okhttpclient 第一行 request request new request.builder url url build 第二行 call call okhttpclient.newcall request 第三行 1 建立 o...

深入理解AQS原始碼解析一

三 最後小結一下 一 概念 我們談到併發,就不得不談reentrantlock鎖 而談到reentrantlock鎖,不得不談一下abstractqueuedsynchronized aqs 類如其名,抽象的佇列式的同步器,aqs定義了一套多執行緒訪問共享資源的同步器框架,許多同步類實現都依賴於它,...