返回catch块上的多个数据



我在试用fetch API,并试图返回fetch错误日志。我所做的是捕获错误并记录catch捕获的错误,它运行良好,但当我在catch块上添加更多console.log时,无论fetch是否捕获错误,它都会执行。为什么会发生这种情况?如何返回catch块上除错误以外的数据?我的代码将对此进行更多解释。提前谢谢。

fetch('api', options)
.then(response => response.json())
.then(data => console.log(data)
})
.catch(err =>
console.log('error', err), //prints error on error 
console.log("this is test") //print regardless of error(prints everytime the program runs even without error)
);

这是因为没有花括号的箭头函数只能包含一条语句,而执行另一个console.log并将其返回值传递给.catch

fetch('api', options)
.then(response => response.json())
.then(data => console.log(data)
)
.catch(function(err){ // first argument
console.log('error', err)
},
console.log("this is test") //second argument
)

如果您希望它只在.catch中执行,请使用以下命令:

fetch('api', options)
.then(response => response.json())
.then(data => console.log(data)
)
.catch(err => {
console.log('error', err), //prints error on error 
console.log("this is test") //prints only on error
}
);

最新更新