今天想要多次then链式,发现自己对then的使用还比较模糊,使用过程中也出现了一些问题,特此记录一下。
function red(){
console.log("红")
}
function yellow(){
console.log("黄")
}
function green(){
console.log("绿")
}
function task(){
new Promise(function(resolve,reject){
setTimeout(() => {
red()
}, 3000);
}).then(()=>{
setTimeout(() => {
green()
Promise.resolve(1)
}, 2000);
}).then(()=>{
setTimeout(() => {
yellow()
}, 1000);
})
}
上面这种写法并不会触发then连续传递。
then使用关键在于then触发必须状态改变
显然没满足,在调用red的settimeout里追加resolve()
red会打印,但不会继续打印yellow和green。因为promise状态只能改变一次,所以对于对于下一个打印green的then来说,除非上面打印red的then返回一个新的promise并且状态改变,否则不执行。
所以task修改为返回新的promise并且执行完函数后改变状态。
function task(time,color){
return new Promise(function(resolve,reject){
setTimeout(() => {
if(color==='red'){
red()
}
if(color==='green'){
green()
}
if(color==='yellow'){
yellow()
}
resolve()
}, time);
})
}
;(function(){
task(3000,'red').then(()=>{
return task(3000,'green')
}).then(()=>{
task(2000,'yellow')
})
})();