用法
function loadData () {
return new Promise(resolve => {
//執行一些操作
resolve();
});
}
loadData().then(() => {
//執行完以後的操作
//可能再返回一個promise
})
源碼分析
function Promise (fn) {
var state = pendding, //狀態,分爲pendding , fullfilled, rejected
callbacks = [],
value; //返回的參數值
//定義then 方法
this.then = function () {
//鏈式結構
return new Promise (
handel({
onFullFilled: onFullFilled || null,
onRejected: onRejected || null,
resolve: resolve,
reject: reject
})
)
}
//處理函數, 處理不同狀態時處理
function handel (callback) {
if (state === ‘pedding’) {
callbacks.push(callback);
return;
}
var handCb = state === 'fullfilled' ? callback.onFullFilled : callback.onRejected;
if (handCb === null) {
handCb = state === ‘fullfilled’ ? callback.resolve: callback.onRejected;
handCb (value);
return;
}
try {
let tempRet = handCb(value);
resolve(tempRet );
} catch (e) {
reject(e);
}
}
//resolve函數變狀態
function resolve (value){
if (value && ( isObject(value) || isPromise(value))){
var then = value.then;
if (isPromise(then){
then.call(value, resolve, reject);
}
}
value = value;
state = 'fullfilled';
excute();
}
function isObject (string){
return Object.prototype.toString.call(string) === ‘[ object object]’;
}
function isPromise (string) {
return Object.prototype.toString(string) === ‘[object promise]’;
}
//reject函數變狀態
function reject (reason){
value =reason;
state = ‘rejected’;
excute();
}
fucntion excute () {
setTimeout(() => {
callbacks.forEach(callbak => {
handle(callback);
})
}, 0)
}
fn(resolve);
}