javascript - 处理 promise 错误的最佳方法是什么?

标签 javascript angular typescript promise es6-promise

我有一个配置加载函数,它从一个 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/

相关文章:

javascript - Bootstrap 4 下拉菜单未显示

javascript - ESnext 中的属性初始化器语法

Angular 2路由器导航功能不起作用

angular - 在 Angular2 服务中包装外部脚本

angularjs - 我可以在函数中创建一个 TypeScript 类并引用它的参数吗?

node.js - 导出变量 'router' 具有或正在使用来自外部模块的名称 'Router' 但无法命名

javascript - 记住页面导航之间展开的节点

javascript - 单击选择标签中的选项并检查值时创建创建输入

2016 年的 Typescript 工作流程

javascript - channel 网址