简易promise的实现(二)

时间:2023-03-09 13:02:57
简易promise的实现(二)

code

上一章中我们遇到了两个问题

1.异步调用顺序的问题

2.then返回一个promise的问题

思考

如果控制异步回调的顺序?

因为异步操的时间作我们无法控制,但是我们只需要按顺序执行回调函数就好了

也就是说

then里面的回调,我们等调用 resolve方法之后(确保异步操作完成),再来执行

操作

用一个变量nextResolve 来保存then的 回调函数

放在resolve之后调用

   function MyPromise(fn) {
var res = null,
       callback = null,
nextResolve = null;
function resolve(val) {
if(typeof(callback) === 'function'){
res = callback(val);
}
nextResolve(res);
} function reject(val){
if(typeof(callback) === 'function'){
res = callback(val);
}
nextResolve
} this.then = function (cb) {
callback = cb;
return new MyPromise(function(resolve,reject){
nextResolve = resolve;
})
}; fn(resolve,reject);
}

结果是

简易promise的实现(二)

是我们要的结果。

现在到第二个问题

如果返回的是一个promise呢? 下面这种是我们的连续异步操作

   http('www.123.com').then(function(res){
console.log(res)
return http('www.456.com');
}).then(function(res){
console.log(res)
})

直接把 promise对象返回了,不是promise执行之后的值

简易promise的实现(二)

这个时候我们要的是 www.456.com

也就是说我们要执行 then方法,才能得到 www.456.com

现在我们只要判断,如果是返回一个promise对象,我们就执行他的resolve方法 就能拿到它回调的值了。

注意 return

    function MyPromise(fn) {
var res = null,
       callback = null,
nextResolve = null;
function resolve(val) { if(typeof(callback) === 'function'){
res = callback(val);
}
if(res && res instanceof MyPromise){
var newThen = res.then
newThen.call(res,nextResolve);
return;
} if(typeof(nextResolve) === 'function'){
nextResolve(res);
}
} function reject(val){
if(typeof(callback) === 'function'){
res = callback(val);
}
nextResolve
} this.then = function (cb) {
callback = cb;
return new MyPromise(function(resolve,reject){
nextResolve = resolve;
})
}; fn(resolve,reject);
}

简易promise的实现(二)

成功返回

下一章我们介绍 ,reject 和catch的写法