-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
从一道promise题说说promise的实现 #6
Comments
初看这个题目,小子我心头淡然一笑,1,4,2,3 答案不假思索就脱口而出。这个题目不就是想考察我们js的Event Loop嘛。然后后面看到答案,瞬间感觉跳进了一个坑里。下面一个一个的拆解开来说
根据上面的代码可以看出来,excutor确实是new的同时就会执行了的。
Promise.prototype.then = function(onResolve,onReject){
var self = this;
var promise2,
onResolve = typeof onResolve === 'function' ? onResolve : function(value){},
onReject = typeof onReject === 'function' ? onReject : function(){reject};
if(self.status === 'resolved'){
return promise2 = new Promise(function(resolve,reject){
try{
var x = onResolve(self.data);
if(x instanceof Promise){
x.then(resolve,reject)
}
resolve(x);
}catch (e){
reject(e);
}
})
}
if(self.status === 'rejected'){
return promise2 = new Promise(function(resolve,reject){
try{
var x = onReject(self.data);
if(x instanceof Promise){
x.then(resolve,reject)
}
resolve(x);
}catch (e){
reject(e);
}
})
}
if(self.status === 'pending'){
return promise2 = new Promise(function(resolve,reject){
self.onResolveCallback.push(function(value){
try{
var x = onResolve(self.data);
if(x instanceof Promise){
x.then(resolve,reject)
}
resolve(x);
}catch (e){
reject(e);
}
})
self.onRejectCallback.push(function(value){
try{
var x = onReject(self.data);
if(x instanceof Promise){
x.then(resolve,reject)
}
resolve(x);
}catch (e){
reject(e);
}
})
})
}
} 看完了代码,回到原有的题目上,在new Promise的时候,直接执行了reject的逻辑,此时这个Promise的状态为reject,因此在then的时候,会执行如下这段代码
所以,就得到了我们的最终答案,1,4,3
|
状态从pending变成reject就直接进入then里面的onReject回调了 1,4,3 |
是的,但是上个月所有的面试者几乎都答错了。。。 |
我觉得这道题目和 Promise 的实现好像没什么太大关系 |
先来看下这个题目
The text was updated successfully, but these errors were encountered: