Reputation: 815
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);
});
});
}
Upvotes: 0
Views: 138
Reputation: 42500
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.
Upvotes: 0
Reputation: 888017
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;
});
Upvotes: 3