为什么这两个Promise呢?捕获回调被调用? [英] Why do both Promise's then & catch callbacks get called?
问题描述
我有以下代码,执行完毕后,将返回被拒绝和成功:
{pre>
// javascript promise
var promise = new Promise(function(resolve,reject){
setTimeout(function(){reject()},1000)
});
promise
.catch(function(){console.log('rejected')})
.then(function(){console.log('success')});
任何人都可以解释为什么要记录成功?
然后
回调被调用,因为 catch
回调是在它之前,而不是之后。该拒绝已经由 catch
处理。如果您更改了订单(即($ code> promise.then(...)。catch(...))),然后
回调将不会执行。
MDN 表示 .catch()
方法返回一个新的承诺,解析为返回值。你的catch回调并不返回任何东西,所以承诺是通过 undefined
值解决的。
I have the following code and when it's executed, it returns both "rejected" and "success":
// javascript promise
var promise = new Promise(function(resolve, reject){
setTimeout(function(){reject()}, 1000)
});
promise
.catch(function(){console.log('rejected')})
.then(function(){console.log('success')});
Could anyone explain why success is logged?
The then
callback gets called because the catch
callback is before it, not after. The rejection has already been handled by catch
. If you change the the order (i.e. (promise.then(...).catch(...)
)), the then
callback won't be executed.
MDN says that the .catch()
method "returns a new promise resolving to the return value of the callback". Your catch callback doesn't return anything, so the promise is resolved with undefined
value.
这篇关于为什么这两个Promise呢?捕获回调被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!