在嵌套 Promise 中抛出 catch 块来触发外部 Promise 的 catch 块,是否有其他更干净的方法?

Ric*_*ard 5 javascript promise es6-promise

我正在嵌套 Promise,我必须知道嵌套的 Promise 是被拒绝的 Promise 还是已完成的 Promise,才能知道是否触发外部 Promise 链的 catch。为了区分嵌套 Promise 是被拒绝还是被履行,我throw在嵌套 Promise 中使用 acatch来表示拒绝;throw当我的嵌套 Promise 中没有时,总是表明履行catch。请看下面的例子:

let test = new Promise((resolve, reject) => {
  resolve(42);
}).then((e) => {
  console.log(e);
  return new Promise((resolve, reject) => { //Error happens inside this nested Promise
    resolve(32);
  }).then((e) => {
    console.log(e);
    //Run other processes that may lead to an error
  }).catch((e) => { //I added this catch block for error detection, whatever error it might be
    console.log(e);
    throw(e); //I'm throwing (e) from the inner Promise's catch so that the returned Promise in the outer then is a rejected Promise, which will be "caught" by the catch block of the outer Promise
  });
}).catch((e) => {
  console.log(e); //I handle error that happen may either in the inner Promise or the outer Promise here
});
Run Code Online (Sandbox Code Playgroud)

上面显示了我在嵌套 Promise 块throw中使用 -ing的含义。catch以上是指示嵌套 Promise 失败的标准方法,还是有其他更干净的方法来实现我想要的?正如您所看到的,我实际上throw在嵌套的 Promise 中使用了两次 -ing 来表示拒绝。有没有一种方法可以让我throw一次并指示 Promise 拒绝?

编辑

catch我在内部 Promise外部 Promise 中使用块的原因:我想检测内部 Promise 内的错误,并且所说的检测是使用内部catch块完成的;我想使用相同的处理程序来处理内部 Promise 或外部 Promise 中可能发生的错误,这是使用我的外部catch块完成的。因为catch-ing 在我的内部 Promise 中return的 Promise 被认为已满足我的外部 Promise 的块,所以我决定在我的内部块中then使用来表明它实际上没有满足,如果它到达内部块。我还编辑了我的代码,以表明我内心的 Promise 中发生的错误不是由我在代码中手动触发的。throwcatchcatchthrow

Edw*_*win 5

我认为最干净的方法是使用 async/await。但在去那里之前,您的问题是当内部承诺失败时如何不运行外部承诺?

下面的例子:

  • 当内心的承诺被拒绝时,链条就会停止。
  • 当外在的应许被拒绝时,内在的应许就已经实现了。

const fun42 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() =>{
            resolve(42)
            reject('something at fun 42 went wrong')
        }, 500)
    })
}

const fun32 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() =>{
            //resolve(32)
            reject('something at fun 32 went wrong')
        }, 500)
    })
}

fun32().then(x => {
    console.log(x)
    return fun42()
}).then( y => {
    console.log(y)
}).catch (e => {
    console.log(e)
})
Run Code Online (Sandbox Code Playgroud)