1

I was looking at this question asked and the answer makes sense

What is the explicit promise construction antipattern and how do I avoid it?

However if you just want to simply put a log message in the function or something simple is there any way of avoiding having to create a new promise like this

function getStuffDone(param) {
    return new Promise(function(resolve, reject) {
        // using a promise constructor
        myPromiseFn(param+1)
        .then(function(val) {
            console.log("getStuffDone executing");
            resolve(val);
        }).catch(function(err) {
            console.log("getStuffDone error");
            reject(err);
        });
    });
}

And what if you also wanted a log message before the promise gets run in this position? Does this make things more difficult?

function getStuffDone(param) {
    return new Promise(function(resolve, reject) {
        // using a promise constructor
        console.log("getStuffDone starting");
        myPromiseFn(param+1)
        .then(function(val) {
            console.log("getStuffDone executing");
            resolve(val);
        }).catch(function(err) {
            console.log("getStuffDone error");
            reject(err);
       });
   });
}
Community
  • 1
  • 1
user2802557
  • 747
  • 1
  • 9
  • 19

2 Answers2

4

Just return or rethrow the original value in your logging callbacks, and then() will give you back a promise of the same thing.

The whole point of promises is that they're easy to chain like that.

return myPromiseFn(param+1)
     .then(function(val) {
         console.log("getStuffDone executing");
         return val;
     }).catch(function(err) {
         console.log("getStuffDone error");
         throw err;
     });
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I was still wondering about the edit I added to my question. In the scond case to accommodate the 'getStuffDone starting' log I would need to wrap it in a new comment? Though I guess the better solution is to go without the log in this case. – user2802557 Mar 21 '16 at 13:30
  • @user2802557: You can call that synchronously before calling the other function. – SLaks Mar 21 '16 at 13:45
0

What SLaks said. As an alternative to return/rethrow, it also works to branch your chain:

var p = myPromiseFn(param+1);
p.then(val => console.log("getStuffDone executing"),
       err => console.log("getStuffDone error"));
return p;

Each branch is an independent chain, so the logging does not affect the returned p in any way.

jib
  • 40,579
  • 17
  • 100
  • 158