【问题标题】:What is the meaning of 'catch(...)' with no '{...}' block following it?'catch(...)' 后面没有'{...}' 块是什么意思?
【发布时间】:2018-10-30 17:07:51
【问题描述】:

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

【问题讨论】:

标签: javascript node.js


【解决方案1】:

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

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

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

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

【讨论】:

  • 我想你的意思可能是try { resolve(); }。另外,我怎么能在这里finally
  • 不,我拒绝了,以表明也可以从 try 中调用 catch。另外,更新了我关于最终如何做的答案。
【解决方案2】:

在您的情况下,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

并检查如何以替代方式执行finally

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      问题 1:只要 promise 获得“rejected”,Promise API 就会调用传入 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:您列出的四种方法中的第一种方法应该有效。

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 2011-02-11
        • 2011-01-18
        • 1970-01-01
        • 2013-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多