简体   繁体   English

如何在ES6 Promise链中传播拒绝?

[英]How to propagate a reject in a ES6 Promise chain?

Usually the two Promise objects are created across function calls. 通常,两个Promise对象是跨函数调用创建的。 I have put the promises together showing what I would expect to happen: 我把承诺放在一起展示了我期望发生的事情:

new Promise((resolve, reject) => {

    //function call with returned promise...

    return new Promise((resolve, reject) => {

      reject("rejectCall_2")  //Prints nothing

    })

}).catch( e1 => {
  console.log('e1',e1) 
})

This should have propagated the reject into my parent promise. 这本应该将拒绝传播到我的父承诺中。 How can I capture the rejectCall_2 in the outer promise? 如何在外部承诺中捕获rejectCall_2?

You don't return anything from inside new Promise . 你不会new Promise返回任何东西。 Whatever you return is just thrown away, What you do is resolve and reject. 无论你返回什么,都会被抛弃,你所做的就是解决和拒绝。 If you want to "return" something, including another promise, what you do is resolve with that something. 如果你想“回报”某些东西,包括另一个承诺,你所做的就是解决这个问题。

So what you want is 所以你想要的是

new Promise((resolve, reject) => {
    //function call with returned promise...
    resolve(new Promise((resolve, reject) => {
    ^^^^^^^
      reject("rejectCall_2")
    }));
}).catch(e1 => {
  console.log('e1', e1) 
})

Tested with babel-node. 用babel节点测试。

FWIW, you might as well use the immediate return fat-arrow format and save yourself a few curly braces: FWIW,您也可以使用立即返回胖箭头格式并为自己节省一些花括号:

new Promise((resolve, reject) => 
    resolve(new Promise((resolve, reject) => 
      reject("rejectCall_2")
    ));
).catch( e1 => console.log('e1',e1));

I would take note of the comments which suggest you may be guilty of the "explicit promise constructor anti-pattern', where you construct a promise only to resolve or reject it with some other promise that you could have just used in the first place. I'm assuming your example is an artificial one designed to showcase your particular issue. 我会注意到这些意见表明你可能会犯“明确的承诺构造函数反模式”,你构建一个承诺,只能解决或拒绝它与你刚才可能刚刚使用的其他承诺。我假设你的例子是一个旨在展示你的特定问题的人造例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM