' catch(...)'是什么意思?没有' {...}'阻止它?

时间:2018-05-21 04:46:55

标签: javascript node.js

我在一些npm包中看到了一段类似于下面的代码:

this.func(callback).then(function() {
  ...
  return x;
}).then(function() {
  ...
  return y;
}).then(function() {
  ...
  return z;
}).then(function() {
  mocha.run(function(failures) {
    ...
    callback(failures);
  });
}).catch(callback);

问题:

  1. 有人可以解释这个catch(callback)的含义是什么,后面没有{...}块?

  2. 我想添加finally子句来执行callback,但我尝试的每种语法似乎都失败了:

    • .catch(callback).finally(callback);
    • .catch(callback).finally(callback());
    • .catch(callback).finally{callback()};
    • .catch(callback).finally(){callback()};

    有人可以帮忙吗?

  3. 谢谢。

4 个答案:

答案 0 :(得分:0)

在你的情况下,然后和catch引用Promise的原型而不是本机catch实现。请查看此示例以更好地理解它:

let doSomething = () {
   return new Promise((resolve, reject) => {
        try { 
         reject(); 
       } catch(e) {
         reject(); 
        } finally {
          console.log('done');
        }
   });
}

doSomething().then(() => {}).catch(() => {});

请注意,您将执行任何操作,将调用catch。

答案 1 :(得分:0)

在您的情况下,catch函数指的是您在callback块中传递的catch函数

//first case
function callback(){}

catch(callback);
//second case 
catch(function(){})

这两种情况都有效

finally它仍然缺乏浏览器支持,您可以在此页面底部查看

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

并以另一种方式检查此finally

what is the equivalent of bluebird Promise.finally in native ES6 promises?

答案 2 :(得分:0)

你可以这样试试。 有关承诺的更多详细信息:see here

doSomething(()=>{//do something})
.then(()=>{})
.catch((error)=> { console.log(error); })
.finally(()=> { //finally block here });

答案 3 :(得分:0)

问题1:只要承诺获得" Promise API" rejected就会调用catch中传递的函数。请考虑以下代码:

// method 1: define the callback function
var callback = function(error){
    console.error(error); // console the error
};
this.func.then(...).catch(callback);

// method 2: pass the function assigned to "callback" variable itself 

this.func.then(...).catch(function(error){
    console.error(error); // console the error
});

您只是告诉上面(在您的代码中)函数调用返回的承诺: "嘿,无论何时你没有完成任务,都要调用我(或其他人)定义的函数callback。"

问题2:您的四种方法列表中的第一种方法应该有效。