Promise
promise坠落现象
Promise.resolve('foo').then(Promise.resolve('bar')).then(res=>{
console.log(res)
})
<!-- log 'foo' -->
-
以上输出为
foo
.会很奇怪 -
Promise的then方法的参数期望是函数,传入非函数则会发生值穿透。
-
因为给
then方法传递了一个非函数(比如promise对象)的值
代码会理解为then(null)
, 因此导致前一个promise的结果产生了坠落的效果 -
更新
Promise.resolve('foo').then(()=>{ return Promise.resolve('bar') }).then(res=>{ console.log(res) }) <!-- log 'bar' -->
与 setTimeout 执行顺序
setTimeout(()=>{
console.log('setTimeout')
})
let p1 = new Promise((resolve)=>{
console.log('Promise1')
resolve('Promise2')
})
p1.then((res)=>{
console.log(res)
})
console.log(1)
<!-- log `1 , Promise1 , Promise2 , setTimeout` -->
实现简单的 Promise
function Promise(fn){
var status = 'pending';
function successNotify(){
status = 'fulfilled'
toDoThen.apply(undefined, arguments);
}
function failNotify(){
status = 'rejected'
toDoThen.apply(undefined, arguments);
}
function toDoThen(){
setTimeout(()=>{
if(status === 'fulfilled'){
for(let i = 0; i < successArray.length; i++){
successArray[i].apply(undefined, arguments)
}
}
if(status === 'rejected'){
for(let i = 0; i < failArray.length; i++){
failArray[i].apply(undefined, arguments)
}
}
})
}
var successArray = [];
var failArray = [];
fn.call(undefined,successArray,failArray);
return {
then: function(successFn,failFn){
successArray.push(successFn);
failArray.push(failFn);
return undefined;
}
}
}
网友评论