【问题标题】:Javascript Promise: Why is caught Exception still logged as uncaught?Javascript Promise:为什么捕获的异常仍然记录为未捕获?
【发布时间】:2016-11-23 11:09:10
【问题描述】:

当我构建我的 Promise 并调用失败函数时,错误应该被 .catch 函数捕获,对吗?但是在 console.log 中,我仍然认为它是未捕获的(也触发了 .catch 函数)。为什么?或者这是故意的?我想我在概念上有些错误,希望得到启发!

考虑以下示例:

var A = {
  loadingPromise: null,
  loadingPromiseFail: null,
  loadingPromiseResolver: null,

  init: function() {
    this.loadingPromise = new Promise(
      function(resolve, fail) {
        this.loadingPromiseResolver = resolve;
        this.loadingPromiseFail = fail;
      }.bind(this)
    );

    this.loadingPromise.then(function(data) {
      console.log('success');
    }.bind(this));

    this.loadingPromise['catch'](function(e, x) {     
      console.log('error', e);
    }.bind(this));
  },

  doSomething: function() {
    setTimeout(function(){ 
     this.loadingPromiseFail('404');
    }.bind(this), 1000);
  }

}

A.init();
A.doSomething();

console.log:

error 404
uncaught exception: 404

为什么是第二个?

也在这里: https://jsfiddle.net/Paflow/4g7yj38b/6/

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    这段代码

    this.loadingPromise.then(function(data) {
      console.log('success');
    }.bind(this));
    

    没有catch,所以错误确实没有被捕获

    这就是你应该如何编写代码以正确使用 Promises

    var A = {
      loadingPromise: null,
      loadingPromiseFail: null,
      loadingPromiseResolver: null,
    
      init: function() {
        this.loadingPromise = new Promise(
          function(resolve, fail) {
            this.loadingPromiseResolver = resolve;
            this.loadingPromiseFail = fail;
          }.bind(this)
        );
    
        this.loadingPromise.then(function(data) {
          console.log('success');
        }.bind(this)).catch(function(e, x) {
          console.log('error', e);
        }.bind(this));
      },
    
      doSomething: function() {
        setTimeout(function() {
          this.loadingPromiseFail('404');
        }.bind(this), 1000);
      }
    
    }
    
    A.init();
    A.doSomething();
    

    https://jsfiddle.net/4g7yj38b/7/

    重点是,您可以将多个 .then(实际上是 .catch)添加到 Promise ... 每个“链”都是独立的,因此您应该有一个 .catch每个“链”都避免此控制台错误,即使这对其余代码没有实际影响

    【讨论】:

    • 好的,谢谢,我不认为 catch() 函数是附加到 then() 函数的东西,而是存在于同一级别的东西。我很可能已经预料到了,您也可以添加几个 catch() 函数,并且在任何失败的情况下,都会调用所有函数。正如我所想,一些概念上的误解。谢谢你的解释!
    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2020-12-10
    • 2015-03-16
    • 2020-07-31
    • 2021-10-05
    相关资源
    最近更新 更多