在 Promise 中混淆错误和拒绝 [英] Confuse about error and reject in Promise
问题描述
全部:
我对 JS Promise 还很陌生,当谈到 Promise 链时,有一个令人困惑的地方,比如我有一个像 Promise 链:
I am pretty new to JS Promise, there is one confuse when it comes to Promise chaining, say I have a promise chaining like:
var p = new Promise(function(res, rej){
})
.then(
function(data){
},
function(err){
})
.then(
function(data){
},
function(err){
})
.catch(
function(err){
})
让我困惑的是:
- 函数(err)何时被调用,catch 何时被调用?
- 如何在
then
中解决和拒绝?
- When the function(err) get called and when the catch get called?
- How to resolve and reject in
then
?
谢谢
推荐答案
使用 Promise 的公式是:
The formular for using a Promise is:
var p = new Promise(function(resolve, reject) {
var condition = doSomething();
if (condition) {
resolve(data);
} else {
reject(err);
}
});
.catch
没有什么特别的,只是.then (undefined, func)
的糖,但是.catch
更清楚传达它纯粹是一个错误处理程序.
There is nothing special about .catch
, it is just sugar for .then (undefined, func)
, but .catch
more clearly communicates that it is purely an error handler.
如果一个 Promise
没有解析,并且其中没有提供拒绝回调,它会向前跳到链中的下一个 .then
,其中包含一个拒绝回调.拒绝回调是 reject(err)
.
If a Promise
does not resolve and no rejection callback is provided in it, it skips forward to the next .then
in the chain with a rejection callback in it. The rejection callback is the reject(err)
.
有关更详细的说明,请参阅:Javascript Promises - 来来回回.
For more detailed explanations see: Javascript Promises - There and Back again.
也就是说:在您的示例中,只有在前面的拒绝回调中有错误时才会调用 .catch
.那是 reject(err)
函数本身存在错误 - 这与前面的 Promise
未解析无关.
That is: in your example the .catch
only gets called if the preceding rejection callback has an error in it. That is there is an error in the reject(err)
function itself - which has nothing to do with the preceding Promise
not resolving.
您基本上可以将自己限制在 .then
链末端的 .catch
中的拒绝回调.任何.then
中的任何Error
都将落入.catch
.不过有一个微妙之处:.catch
中的任何错误都不会被捕获.
You can essentially limit yourself to a rejection callback in the .catch
at you end of the .then
chain. Any Error
in any .then
will then fall through to the .catch
. One subtlety though: any error in the .catch
is not caught.
这篇关于在 Promise 中混淆错误和拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!