javascript - 是否可以在不向控制台发送错误消息的情况下停止链?

标签 javascript promise chain

<分区>

使用以下代码,当我拒绝 promise 时,我看到了第一个 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');
});

最佳答案

两个 .then(success, error) 回调都返回 promises。

即:

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
})

关于javascript - 是否可以在不向控制台发送错误消息的情况下停止链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39021845/

相关文章:

javascript - 将 promise 置于待处理状态

javascript - 从第一个调用的 promise 中获取第二个调用的响应

javascript - 如何在谷歌街景中保存 "zoom"图像

javascript - 删除 chrome 扩展中的注入(inject)脚本

javascript - 无法将没有 YogaNode 的子级添加到没有测量函数的父级

javascript - 使用 Promise 设置一个变量以从回调函数中获取返回值

javascript增强原型(prototype)和链

conditional-statements - RxJs:如何有条件地链接 BehaviorSubject 的 observable?

javascript - 如何使用 bluebirdjs 按顺序链接 promise ?

javascript - RequiredField 验证器未触发