函數(shù)式編程:
JavaScript函數(shù)式編程指南異步編程:
異步編程Promise源碼
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
function MyPromise(fn) {
const _self = this;
this.value = undefined;
this.reason = undefined;
this.status = PENDING;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
function resolve(value) {
// if (value instanceof MyPromise) {
// return value.then(resolve, reject);
// }
if (_self.status === PENDING) {
setTimeout(() => {
_self.status = FULFILLED;
_self.value = value;
_self.onFulfilledCallbacks.forEach(callback => callback(_self.value));
}, 0)
}
}
function reject(reason) {
if (_self.status === PENDING) {
setTimeout(function() {
_self.status = REJECTED;
_self.reason = reason;
_self.onRejectedCallbacks.forEach(callback => callback(_self.reason));
}, 0)
}
}
try {
fn(resolve, reject);
} catch (e) {
reject(e);
}
}
// 用來(lái)解析回調(diào)函數(shù)的返回值x惰聂,x可能是普通值也可能是個(gè)promise對(duì)象
function resolvePromise(bridgepromise, x, resolve, reject) {
// 2.3.1規(guī)范宠漩,避免循環(huán)引用
if (bridgepromise === x) {
return reject(new TypeError('Circular reference'));
}
let called = false; // 只允許調(diào)用一次resolve/reject,以第一次為準(zhǔn)
// 2.3.3規(guī)范,如果 x 為對(duì)象或者函數(shù)
if (x != null && ((typeof x === 'object') || (typeof x === 'function'))) {
try {
// 是否是thenable對(duì)象(具有then方法的對(duì)象/函數(shù))
//2.3.3.1 將 then 賦為 x.then
let then = x.then; // 如果then具有g(shù)etter屬性预吆,此時(shí)獲取會(huì)發(fā)生異常
if (typeof then === 'function') {
// 2.3.3.3 如果 then 是一個(gè)函數(shù),以x為this調(diào)用then函數(shù)啦鸣,且第一個(gè)參數(shù)是resolvePromise涣狗,第二個(gè)參數(shù)是rejectPromise
then.call(x, y => {
if (called) return;
called = true;
// 一直解析,直到結(jié)果為常量為止
resolvePromise(bridgepromise, y, resolve, reject);
}, error => {
if (called) return;
called = true;
reject(error);
})
} else { // 是一個(gè)普通對(duì)象
// 2.3.3.4 如果 then不是一個(gè)函數(shù)更啄,則 以x為值fulfill promise稚疹。
resolve(x);
}
} catch (e) {
// 2.3.3.2 如果在取x.then值時(shí)拋出了異常,則以這個(gè)異常做為原因?qū)romise拒絕祭务。
if (called) return;
called = true;
reject(e);
}
} else { // 普通值内狗,直接返回即可
// 如果x是一個(gè)普通值怪嫌,就讓bridgePromise的狀態(tài)fulfilled,并把這個(gè)值傳遞下去
resolve(x);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
const _self = this;
let bridgePromise;
//防止使用者不傳成功或失敗回調(diào)函數(shù)柳沙,所以成功失敗回調(diào)都給了默認(rèn)回調(diào)函數(shù)
// 值的穿透?jìng)鬟f
onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value;
onRejected = typeof onRejected === "function" ? onRejected : error => { throw error };
if (this.status === FULFILLED) {
return bridgePromise = new MyPromise((resolve, reject) => {
setTimeout(() => { // 因?yàn)閚ew過(guò)程中還未拿到bridgePromise岩灭,所以這里走異步,以拿到promise2
try {
// 函數(shù)返回值
let x = onFulfilled(_self.value);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e); // 如果執(zhí)行函數(shù)時(shí)拋出失敗赂鲤,那么會(huì)走向下一個(gè)失敗狀態(tài)
}
}, 0);
})
}
if (this.status === REJECTED) {
return bridgePromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
let x = onRejected(_self.reason);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
}
if (this.status === PENDING) {
return bridgePromise = new MyPromise((resolve, reject) => {
_self.onFulfilledCallbacks.push((value) => {
try {
let x = onFulfilled(value);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
});
_self.onRejectedCallbacks.push((reason) => {
try {
let x = onRejected(reason);
resolvePromise(bridgePromise, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
}
}
//catch方法其實(shí)是個(gè)語(yǔ)法糖噪径,就是只傳onRejected不傳onFulfilled的then方法
MyPromise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
}
MyPromise.prototype.finally = function(callback) {
return this.then(value => {
return MyPromise.resolve(callback()).then(() => value)
}, reason => {
return MyPromise.resolve(callback()).then(() => { throw reason })
})
}
MyPromise.all = function(promises) {
let result = [];
let count = 0;
return new MyPromise(function(resolve, reject) {
function addData(key, value) {
result[key] = value
count++
if (count === promises.length) {
resolve(result)
}
}
for (let i = 0; i < promises.length; i++) {
let current = promises[i]
if (current instanceof MyPromise) {
current.then(value => addData(i, value), reason => reject(reason))
} else {
addData(i, promises[i])
}
}
});
}
MyPromise.race = function(promises) {
return new MyPromise(function(resolve, reject) {
for (let i = 0; i < promises.length; i++) {
promises[i].then(function(data) {
resolve(data);
}, function(error) {
reject(error);
});
}
});
}
MyPromise.resolve = function(value) {
if (value instanceof MyPromise) return value
return new MyPromise(resolve => {
resolve(value);
});
}
MyPromise.reject = function(error) {
if (value instanceof MyPromise) return error
return new MyPromise((resolve, reject) => {
reject(error);
});
}
MyPromise.promisify = function(fn) {
return function() {
var args = Array.from(arguments);
return new MyPromise(function(resolve, reject) {
fn.apply(null, args.concat(function(err) {
err ? reject(err) : resolve(arguments[1])
}));
})
}
}
// 執(zhí)行測(cè)試用例需要用到的代碼
MyPromise.deferred = function() {
let defer = {};
defer.promise = new MyPromise((resolve, reject) => {
defer.resolve = resolve;
defer.reject = reject;
});
return defer;
}
JavaScript基礎(chǔ)知識(shí)
ES2015+疑難點(diǎn)解析
你不知道的JS系列:
徹底搞懂JavaScript函數(shù)執(zhí)行機(jī)制
徹底搞懂JavaScript作用域
徹底搞懂JavaScript之對(duì)象
徹底搞懂JavaScript之類
徹底搞懂JavaScript之原型
徹底搞懂JavaScript中的this
徹底搞懂JavaScript數(shù)據(jù)類型
JavaScript類型轉(zhuǎn)換
JavaScript語(yǔ)句TypeScript疑難點(diǎn)
TypeScript疑難解析
- JavaScript性能優(yōu)化
JavaScript性能優(yōu)化
JS垃圾回收詳解