promise的异常链

var Q = require("q");      //需要先用npm安装node.js q模块
var retPromise = function(isSuc){
    var deferred = Q.defer();
    if(isSuc){
        deferred.resolve("success");
    }else{
        deferred.reject("fail");
    }

    return deferred.promise;
};

retPromise(false).then(function(data){
    console.log(data + ", enter the first resolve func");
    throw new Error(data + ", but threw error");
}).then(function(data){
    console.log(data + ", enter the second resolve func");
}).then(function(data){
    console.log(data + ", enter the third resolve func");
}, function(error){
    console.error(error + ", enter the first reject func");
}).then(function(data){
    console.log(data + ", enter the fourth resolve func");
},function(error){
    console.error(error + ", enter the second reject func");
});

node执行上面的脚本,结果如下:
fail, enter the first reject func
undefined, enter the fourth resolve func

以上结果说明:
1)一个reject的promise对象会沿着其后的promise链寻找reject处理函数,直到找到为止,并调用该reject处理函数;
2)reject处理函数成功执行之后,如果继续使用then方法,仍会按照正常的promise流程走下去,相当于返回了一个resolve的promise对象

手动抛个异常,如下

retPromise(true).then(function(data){
    console.log(data + ", enter the first resolve func");
    throw new Error(data + ", but threw error");
}).then(function(data){
    console.log(data + ", enter the second resolve func");
}).then(function(data){
    console.log(data + ", enter the third resolve func");
}, function(error){
    console.error(error + ", enter the first reject func");
}).then(function(data){
    console.log(data + ", enter the fourth resolve func");
},function(error){
    console.error(error + ", enter the second reject func");
});

node运行结果如下:
success, enter the first resolve func
Error: success, but threw error, enter the first reject func
undefined, enter the fourth resolve func

手动抛出异常,相当于返回一个reject的promise,结果分析与上同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值