es6的Promise链式调用的实例

// .then()接受两个函数作为参数,分别代表fullfilled和rejected
// .then()返回一个新的promise实例,所以它可以链式调用
// 当前面的Promise状态改变时,.then()根据其最终状态,选择特定的状态响应函数的执行
// 状态响应函数可以返回新的Promise,或其他值
// 如果返回的是新的promise,那么下一级的.then()会在新promise状态改变之后执行
// 如果返回其他任何值,则会立即执行下一级.then()

// .then()里面有.then()的情况?
// 因为.then()返回的还是promise实例
// 会等里面的.then()执行完,再执行外面的
// 对于我们来说,此时最好将其展开,会更好读
console.log('start')
new Promise(resolve=>{
    console.log('step 1');
    setTimeout(() => {
        resolve(100)
    }, 0);
})
.then(value=>{
    return new Promise(resolve=>{
        console.log('step 1-1');
        setTimeout(() => {
            resolve(110)
        }, 0);
    })
    .then(value=>{
        console.log('step 1-2');
        return value
    })
    .then(value=>{
        console.log('step 1-3');
        return value
    })
})

.then(value=>{
    console.log(value);
    console.log('step 2');
})
/*
start
step 1
step 1-1
step 1-2
step 1-3
110
step 2
*/
let dosth = () => {
    return new Promise(resolve=>{
        console.log('step 1');
        setTimeout(() => {
            resolve(100)
        }, 0);
    });
}
let Sth = (value)=>{
    return new Promise(resolve=>{
        console.log('step 1-1',value);
        setTimeout(() => {
            resolve(110)
        }, 0);
    })
    .then(value=>{
        console.log('step 1-2');
        return value
    })
    .then(value=>{
        console.log('step 1-3');
        return value
    })
}
let finalHandler = (value) => {
    console.log('step 2',value);
}


console.log('case1')
dosth()
.then(()=>{
    return Sth()
})
.then(finalHandler);
/*
dosth----
        Sth (undefined)-------
                                finalHandler (Sth返回的值)
依次执行:
case1
step 1
step 1-1 undefined
step 1-2
step 1-3
step 2 110
*/


console.log('case2')
dosth()
.then(()=>{
    Sth()
})
.then(finalHandler);
/*
dosth---------
            ---Sth  (undefined)
            ---finalHandler (undefined)
Sth (undefined),finalHandler (undefined)几乎同时执行

case2
step 1
step 1-1 undefined
step 2 undefined
step 1-2
step 1-3
*/


console.log('case3')
dosth()
.then(
    Sth()
)
.then(finalHandler);
/*
dosth--------------
Sth  (undefined)---
                    ---finalHandler (Sth返回的值)
dosth,Sth (undefined)几乎同时执行

case3
step 1
step 1-1 undefined
step 2 100
step 1-2
step 1-3
*/


console.log('case4')
dosth()
.then(
    Sth
)
.then(finalHandler);
/*
dosth--------------
                -----Sth(dosth返回的值)---
                                        ----finalHandler (Sth返回的值)
依次执行:
case4
step 1
step 1-1 100
step 1-2
step 1-3
step 2 110
*/

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值