以推荐的方式停止承诺链执行

时间:2017-04-23 12:20:53

标签: javascript web promise es6-promise

我有一个与此类似的代码:

promise_function().then(()=>{
  //do something
  return another_promise_fucntion();
}).then(() => {
  //do something
  return another_promise_function1();
}).then((result) => {
  //check if result is valid
  if(!result)
     //break chain (how to stop calling the next .then functions ?)
  else
     return another_promise_function2();
}).then(()=>{
   //do something
   return another_promise_function3();
}).catch((err)=>{
   //handle error
});

如果返回的结果无效,我想停止调用下一个.then()函数。

我使用了“throw new Error()”,它运行得很好,但我不确定它是否是推荐的方式。

1 个答案:

答案 0 :(得分:2)

这是Mozilla重新开始的正确方法 您可以在此处查看更多详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining