使用以下代码,当我拒绝承诺时,我会看到第一个console.log,但我也看到了第二个console.log。这是预期的,因为拒绝仅影响下一个“then()”。
问题是,是否有任何运算符等同于循环中的“break”,以便您可以跳出链?快速回答是肯定的,使用非捕获的reject()或throw(),但两种方法都会向控制台发送错误消息(它们会停止整个代码执行吗?)
所以问题是,它可以“干净地”完成吗?
*我的第一个假设是,通过捕获拒绝/错误,这将成功,但事实并非如此
Promise.resolve()
.then(function(){
do stuff
return Promise.resolve();
})
.then(function(){
if (a === 'this')
return Promise.resolve();
else
// is there any "break" equivalent here?
return Promise.reject();
})
.then(function(){
console.log('seen if not rejected');
},function(){
console.log('seen if rejected');
})
.then(function(){
console.log('seen all the time');
});
答案 0 :(得分:1)
当您将第二个参数(onRejected
函数)传递给then
方法时,实际上会捕获拒绝。它也会返回一个承诺,所以你可以继续链接。
如果删除第三个onRejected
中的then
功能,您将在控制台中看到未捕获的异常,例如:
Promise.reject()
.then(function(){
console.log('resolved');
})
.then(function(){
console.log('you cannot see me');
})
// Uncaught (in promise)
是的,如果catch
没有抓住异常,你可onRejected
例外:
Promise.reject()
.then(function(){
console.log('resolved');
})
.catch(function(){
console.log('you can see me');
})
// you can see me
Promise.reject()
.then(function(){
console.log('resolved');
}, function(){
console.log('rejected');
})
.catch(function(){
console.log('you cannot see me');
})
// rejected
关于我的经验,在实际业务场景中,我们通常希望将不相关的逻辑分开。所以我们会在onRejected
中发现拒绝,做某事,然后将异常抛到catch
方法(本身或链接then
):
Promise.reject()
.then(function(){
console.log('resolved');
}, function(e){
console.log('rejected');
throw e
})
.catch(function(){
console.log('you can see me');
})
// rejected
// you can see me
答案 1 :(得分:1)
两个.then(success, error)
回调都会返回承诺。
那是:
Promise.reject()
.then(function () {
// won't be called, as above promise is rejected
}, function () {
// will be called, and returns a resolved promise by default;
// if you want the next error callback to be called,
// you need to return a rejected promise or to throw an error
})
.then(function () {
// 1: called if above .then returns a resolved promise
}, function () {
// 2: called if above .then returns a rejected promise or throws an error
})
答案 2 :(得分:-1)
这是因为你抓住了拒绝。下面的两个块是等价的:
<强>示例1 强>
var stuff = function () {
};
var doStuff = function () {
};
var a = 'notThis';
Promise.resolve()
.then(function () {
doStuff();
return Promise.resolve();
})
.then(function () {
if (a === 'this')
return Promise.resolve();
else
return Promise.reject();
})
.then(function () {
stuff();
}, function () {
console.log('rejected, end of chain');
})
.then(function () {
console.log('only executed if not rejected');
});
<强>示例2 强>
var stuff = function () {
};
var doStuff = function () {
};
var a = 'notThis';
Promise.resolve()
.then(function () {
doStuff();
return Promise.resolve();
})
.then(function () {
if (a === 'this')
return Promise.resolve();
else
return Promise.reject();
})
.then(function () {
stuff();
})
.catch(function () {
console.log('rejected, end of chain');
})
.then(function () {
console.log('only executed if not rejected');
});