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); }
