繁体   English   中英

'catch(...)' 后面没有 '{...}' 块是什么意思?

[英]What is the meaning of 'catch(…)' with no '{…}' block following it?

我在一些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()};

在您的情况下, then 和 catch 指的是 Promise 的原型,而不是本机 catch 实现。 检查这个例子以更好地理解它:

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

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

请注意,无论您做什么,都会调用 catch。

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

//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

并检查this以了解如何finally以替代方式进行。

原生 ES6 承诺中蓝鸟 Promise.finally 的等价物是什么?

你可以这样试试。 有关承诺的更多详细信息: 请参阅此处

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

问题 1: Promise API 会Promise被“ 拒绝”时调用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:您的四种方法列表中的第一种方法应该有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM