自己手写了一个_Promise,运行老师上面的程序,没啥毛病。除了使用宏任务,可以解决嵌套和参数穿透问题。
var _Promise = (function () {
/*使用闭包 保存所有的回调函数 */
var _resolve = [];
var _reject = [];
var _catch;
return function (executor) {
this.print = function () {
console.log(_resolve)
console.log(_catch)
}
this.then = function (resolve, reject) {
resolve && _resolve.push(resolve);
reject && _reject.push(reject);
return this;
}
this.resolve = function (data) {
setTimeout(function () {
let callback = _resolve.shift();
let pro;
callback && (pro = callback(data));
_reject.shift();
}, 0)
}
this.reject = function (error) {
setTimeout(function () {
let callback = _reject.shift();
callback && callback(error);
callback || _catch(error);
}, 0);
}
this.catch = function (callback) {
_catch = callback;
return this;
}
executor(this.resolve, this.reject);
}
})()
function executor(resolve, reject) {
let rand = Math.random();
console.log(1)
console.log(rand)
if (rand > 0.5)
resolve(rand)
else
reject(rand)
}
var p0 = new _Promise(executor);
var p1 = p0.then((value) => {
console.log("succeed-1")
return new _Promise(executor)
})
var p3 = p1.then((value) => {
console.log("succeed-2")
return new _Promise(executor)
})
var p4 = p3.then((value) => {
console.log("succeed-3")
return new _Promise(executor)
})
p4.catch((error) => {
console.log("error")
})
console.log(2)
展开