为什么这两个Promise呢?捕获回调被调用? [英] Why do both Promise's then & catch callbacks get called?

查看:122
本文介绍了为什么这两个Promise呢?捕获回调被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,执行完毕后,将返回被拒绝成功



{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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆