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,结果分析与上同