我有一个配置加载函数,它从一个 json 文件加载一些数据并用它解决一个 promise 。
当我调用加载函数时,我想知道处理错误的更好方法是什么。据我了解,有两种选择。
public config: any = this.configProvider.load()
.then(data => this)
.then(error => console.error(error));
对比
public config: any = this.configProvider.load()
.then(data => this)
.catch(function(err){
console.log(err);
}
最佳答案
此代码不正确:
public config: any = this.configProvider.load()
.then(data => this)
.then(error => console.error(error));
它不会捕获任何错误。错误是被拒绝的 promise 。你需要的是:
public config: any = this.configProvider.load()
.then(data => this, error => console.error(error))
将捕获被拒绝的 promise 的函数作为第二个参数传递。
但是 catch
的方法对我来说更具可读性和直观性:
public config: any = this.configProvider.load()
.then(...)
.then(...)
.then(...)
.catch(function(err){
console.log(err);
}
但您可以通过以下方式实现相同的目的:
public config: any = this.configProvider.load()
.then(...)
.then(...)
.then(..., function(err){
console.log(err);
});
关于javascript - 处理 promise 错误的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45218890/