我有以下代码,当它被执行时,它同时返回">rejected"one_answers">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')});
有人能解释为什么会记录成功吗
then
回调是因为catch
回调在它之前,而不是之后。拒绝已由catch
处理。如果更改顺序(即(promise.then(...).catch(...)
((,则不会执行then
回调。
MDN表示.catch()
方法"返回一个解析回调返回值的新promise"。您的catch回调不返回任何内容,因此promise使用undefined
值进行解析。
有人能解释为什么会记录成功吗?
简而言之:Promise
链中.catch
之后的.then
将始终被执行(除非它本身包含错误(。
理论解释
您的代码实际上只是一个Promise
链,它首先同步执行,然后将其设置为异步完成。Javascript引擎将把任何reject()
或Error
传递给链下的第一个.then
,其中包含reject
回调。拒绝回调是传递给.then
:的第二个函数
.then(
function (){
//handle success
},
function () {
//handle reject() and Error
})
.catch
的使用只是的语法暗示
.then(null, function () {
//handle reject() or Error
})
每个.then
自动返回一个新的Promise
,后续的.then
(或也是.then
的.catch
(可以对其进行操作。
可视化承诺链的流程
您可以通过以下示例可视化代码流:
var step1 = new Promise (function (resolve, reject) {
setTimeout(reject('error in step1'), 1000);
})
var step2 = step1.then(null, function () {
// do some error handling
return 'done handling errors'
})
var step3 = step2.then(function () {
// do some other stuff after error handling
return 'done doing other stuff'
}, null)
setTimeout (function () {
console.log ('step1: ', step1);
console.log ('step2: ', step2);
console.log ('step3: ', step3);
console.log();
console.log ('Asynchronous code completed')
console.log();
}, 2000);
console.log ('step1: ', step1);
console.log ('step2: ', step2);
console.log ('step3: ', step3);
console.log();
console.log ('Synchronous code completed')
console.log();
在运行时将在控制台中产生以下输出:
step1: Promise { <rejected> 'error in step1' }
step2: Promise { <pending> }
step3: Promise { <pending> }
Synchronous code completed
step1: Promise { <rejected> 'error in step1' }
step2: Promise { 'done handling errors' }
step3: Promise { 'done doing other stuff' }
Asynchronous code completed
对于那些成功解决了promise并订购了类似.then
>.catch
的链,但仍然调用了then
和catch
的人,这可能是因为您的then
有一个抛出错误的错误,除非您显式地在catch
中控制台该错误,否则您无法看到该错误。即使在严格模式下,Promises也会吸收错误,这是我最讨厌的事情之一。
const promise = new Promise(resolve => resolve())
.then(() => {
console.log('then');
not.defined = 'This causes the catch to fire even though the original promise resolved successfully.';
})
.catch((e) => {
console.log('catch');
// console.error(e);
});
对我来说,catch()
是在成功承诺后调用的,.then()
中没有错误。
原因是,我听取了一个随着成功承诺而变化的价值观,并运行了一种方法。
这个方法抛出了一个无声的错误,因为它被视为承诺的一部分。
类似于@Timar,对我来说,调用catch的原因是"那么";包含异常代码。所以在执行";那么";正常情况下,当它到达异常代码时,它在"中处理异常;捕获";xD