简体   繁体   中英

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

I see a piece of code similar to the one below in some npm package:

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);

Questions:

  1. What is the meaning of this catch(callback) with no {...} block following it?

  2. I would like to add a finally clause to execute the callback , but every syntax that I'm trying seems to fail:

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

In your case, then and catch refer to Promise's prototype and not to the native catch implementation. Check this example to understand it better:

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

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

Note that anything you'd do, catch will be called.

In your case catch function refers to your callback function which you are passing in catch block

//first case
function callback(){}

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

Both case will work

and for finally It is still lacking browser support, you can check here at bottom of this page

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

and check this for how to do finally in alternative way.

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

you can try like this. For more detail on promise: see here

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

Question 1: The Promise API calls the function passed in the catch whenever a promise gets " rejected ". So consider the following code:

// 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
});

You are just telling the promise returned by the above (in your code) function call(s) that: "Hey, whenever you fail to do the task, call this function callback that I (or someone else) have defined."

Question 2: The first method in your list of four methods should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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