如何将 Promise 'then' 的值发送到 'catch'?

How to send value from Promise 'then' to 'catch'?

我只想问一下,如果 resolve 上的值不是预期的,我应该如何将 resolve promise 传递给 catch

例如

let prom = getPromise();

prom.then(value => {
    if (value.notIWant) {
        // Send to catch <-- my question is here, I want to pass it on the catch.
    }

    // Process data.
}).catch(err => {
    // Pass the error through ipc using json, for logging.
});

我尝试使用 throw,但无法将对象解析为 json,并且只得到一个空对象。

答案:

@BohdanKhodakivskyi 下面的第一个评论就是我想要的答案。

@31py 的回答也是正确的,但@BohdanKhodakivskyi 的解决方案要简单得多,并且会呈现相同的结果。

你可以简单地return一个被拒绝的承诺:

prom.then(value => {
    if (value.notIWant) {
        return Promise.reject('your custom error or object');
    }

    // Process data.
}).catch(err => {
    console.log(err); // prints 'your custom error or object'
});

.catch 实际上处理链中的任何承诺拒绝,因此如果您 return 拒绝承诺,控制会自动流向 catch

为什么你不重新抛出错误? throw new Error("something");

你可以使用外部 functions 来做到这一点:

var processData = function(data) {
   // process data here
}

var logIt = function(data) {
   // do logging here..
}

let prom = getPromise();

prom.then(value => {
    if (value.notIWant) {
        // Send to catch <-- my question is here, I want to pass it on the catch.
        logIt(/*pass any thing*/);
    }

    // Process data.
    processData(data);

}).catch(err => {
      logIt(/*pass any thing*/);
});

只需使用throw value;。你的情况:

prom.then(value => {
    if (value.notIWant) {
        // Send to catch
        throw value;
    }

    // Process data.
}).catch(err => {
    // Pass the error through ipc using json, for logging.
});

另请注意使用 Promise.reject()throw 之间的区别和限制,这在 中有完美的描述。例如,throw 在某些 async 场景中将不起作用。