What is the correct way to distribute .catch in a promise?

I use bluebird to promise the mongoose library. So, currently I find and save data as follows:

    User.findOneAsync({email: req.body.text})
      .then(function(user) {
        user.saveAsync()
          .spread(function(savedUser){
            res.json(savedUser);
          })
          .catch(function(err) {
            res.json({
              status: 500,
              message: 'foo'
            });
          });
      })
      .catch(function(err) {
         res.json({
           status: 500,
           message: 'foo'
         });
      });

The two catch functions are completely identical. This is just a demo, I sometimes have two identical catch functions in practical work. I could split the function inside the catch into my own function. However, I had to write catch functions several times. What is a good approach to avoid duplicate catch functions? Any help would be greatly appreciated.

+4
source share
2 answers

user.saveAsync(). catch. :

 User.findOneAsync({email: req.body.text})
  .then(function(user) {
    return user.saveAsync()
      .spread(function(savedUser){
        res.json(savedUser);
      });
  })
  .catch(function(err) {
     res.json({
       status: 500,
       message: 'foo'
     });
  });

, spread Promise. , . catch, , .

, - :

 User.findOneAsync({email: req.body.text})
 .call("saveAsync")
 .spread(function (savedUser) {
     res.json(savedUser);
 })
 .catch(function(err) {
    res.json({
      status: 500,
      message: 'foo'
    });
 });

promises.

+5

, . , catch. promises catch.

User.findOneAsync({email: req.body.text})
    .then(function(user) {
        return user.saveAsync();
    })
    .spread(function(savedUser){
        return res.json(savedUser);
    })
    .catch(function(err) {
        return res.json({
            status: 500,
            message: 'foo'
        });
    });
+3

Source: https://habr.com/ru/post/1617771/


All Articles