我只是想问一下,如果解决方案上的值不合适,我应该如何将解析承诺传递给catch
。
EG
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解决方案更加简单,并且会产生相同的结果。
只需使用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
之间的区别和限制,this question在throw
中有完美的描述。例如,async
在某些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
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*/);
});
之外使用它:
qazxswpoi