var PENDING = 0,
FULFILLED = 1,
REJECTED = 2;
function noop() {};
Array.isArray = Array.isArray || function (a) {
return Object.prototype.toString.call(a) === '[object Array]';
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor')
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")
}
function Promise(resolver){
this._state = PENDING;
this._deferredState = PENDING;
this._result = null;
this._deferreds = null;
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.resolve = resolve;
Promise.reject = reject;
Promise.all = all;
Promise.race = race;
Promise.prototype = {
constructor : Promise,
then : then,
'catch' : function _catch(onRejection) {
return this.then(null, onRejection);
}
}
/**
* initializePromise 初始化 Promise 并執(zhí)行 回調(diào)
* @param promise Promise對(duì)象
* @param resolver 回調(diào)函數(shù)
* @param resolvePromise 回調(diào)成功后執(zhí)行
* @param rejectPromise 回調(diào)失敗
*/
function initializePromise (promise, resolver) {
try {
resolver(function resolvePromise(value){
_resolve(promise,value)
},function rejectPromise(err){
_reject(promise,err)
})
} catch (e) {
}
}
/**
* [_resolve resolve處理]
* @param promise [Promise對(duì)象]
* @param value [回調(diào)參數(shù)]
*/
function _resolve (promise,value){
if (promise._state !== PENDING) {
return ;
}
promise._result = value;
promise._state = FULFILLED;
finale(promise);
}
/**
* [_reject resolve處理]
* @param promise [Promise對(duì)象]
* @param err [回調(diào)參數(shù)]
*/
function _reject (promise,err){
if (promise._state !== PENDING) {
return ;
}
promise._result = err;
promise._state = REJECTED;
finale(promise);
}
function finale (self) {
if ( self._deferredState === 1 ) {
handle(self, self._deferreds);
self._deferreds = null;
}
}
function handle (self, deferred) {
if (self._state === PENDING) {
if (self._deferredState === 0) {
self._deferredState = 1;
self._deferreds = deferred;
return;
}
}
handleResolved(self, deferred)
}
function handleResolved (self, deferred) {
var cb = self._state === FULFILLED ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
if (self._state === FULFILLED) {
_resolve(deferred.promise, self._value);
} else {
_reject(deferred.promise, self._value);
}
return;
}
cb(self._result);
if ( self._state === REJECTED ) {
_reject(deferred.promise, self._result);
} else {
_resolve(deferred.promise, self._result);
}
}
function Handler(onFulfilled, onRejected, promise){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* [then 異步回調(diào)]
* @param {[function]} resolve [resolve回調(diào)]
* @param {[function]} reject [reject回調(diào)]
*/
function then (resolve,reject) {
var res = new Promise(noop);
handle(this, new Handler(resolve, reject, res));
return res;
}
/**
* @param {[promise]} object 返回一個(gè)promise對(duì)象
* @param {[string]} object 返回一個(gè)promise對(duì)象 并且resolve返回object
*/
function resolve (object) {
var Constructor = this;
if( object &&
typeof object === 'object' &&
object.constructor === Constructor
) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object)
return promise;
}
function reject (object) {
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, object)
return promise;
}
function all (arr) {
if ( !Array.isArray(arr) ) {
return new Error('Array Methods must be provided an Array');
}
var args = Array.prototype.slice.call(arr);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var len = args.length;
var result = [];
function res(i,val) {
if ( val && (typeof val === 'object' || typeof val === 'function') ) {
if (val instanceof Promise ) {
if ( val._state === REJECTED ) reject(val._result);
if ( val._state === FULFILLED ) res(i,value);
if ( val._state === PENDING ) {
val.then(function(value) {
res(i,value)
}, function( error) {
reject(error)
})
}
return;
}
}
result[i] = val;
if (--len === 0) {
resolve(result);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
})
}
function race (arr) {
return new Promise(function (resolve, reject) {
arr.forEach(function(value){
Promise.resolve(value).then(resolve, function(error){});
});
});
}
自己實(shí)現(xiàn)一個(gè)Promise
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蜡坊,“玉大人杠输,你說我怎么就攤上這事★跹茫” “怎么了蠢甲?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)据忘。 經(jīng)常有香客問我鹦牛,道長(zhǎng),這世上最難降的妖魔是什么勇吊? 我笑而不...
- 正文 為了忘掉前任曼追,我火速辦了婚禮,結(jié)果婚禮上汉规,老公的妹妹穿的比我還像新娘礼殊。我一直安慰自己,他們只是感情好针史,可當(dāng)我...
- 文/花漫 我一把揭開白布晶伦。 她就那樣靜靜地躺著,像睡著了一般啄枕。 火紅的嫁衣襯著肌膚如雪婚陪。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼锯玛,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了兼蜈?” 一聲冷哼從身側(cè)響起攘残,我...
- 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎为狸,沒想到半個(gè)月后歼郭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡辐棒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年病曾,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片漾根。...
- 正文 年R本政府宣布寄疏,位于F島的核電站是牢,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏陕截。R本人自食惡果不足惜驳棱,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望艘策。 院中可真熱鬧蹈胡,春花似錦、人聲如沸朋蔫。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽驯妄。三九已至荷并,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間青扔,已是汗流浹背源织。 一陣腳步聲響...
- 正文 我出身青樓缘屹,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親侠仇。 傳聞我的和親對(duì)象是個(gè)殘疾皇子轻姿,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- 刷手機(jī)。 鄰家小妹這個(gè)評(píng)價(jià)逻炊,真的是辣眼睛互亮。 揮霍青春的人是我,只思進(jìn)取的人是我余素。 25豹休。 似乎真的到了很尷尬的年齡...
- 今年的北京的確很冷屏积,但是因?yàn)槟愕拇嬖谖业檬植辉俦湟搅「兄x一路有你的陪伴,讓我這顆無處安放的心炊林,有了棲息之地姥卢!...