Suppose I have a function that will return a promise that is based on some input value that need to be calculated first. It seems that there are two ways to do this.
Example 1:
function foo(val) {
var newVal = val + 100;
var anotherVal = newVal % 12;
var returnVal = anotherVal * 3;
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(returnVal);
}, 1000);
});
}
foo(10).then(function(val) {
console.log(val);
});
Example 2:
function foo(val) {
return new Promise(function(resolve, reject) {
var newVal = val + 100;
var anotherVal = newVal % 12;
var returnVal = anotherVal * 3;
setTimeout(function() {
resolve(returnVal);
}, 1000);
});
}
foo(10).then(function(val) {
console.log(val);
});
The first example keeps all of the setup outside of the promise function. And the second moves all of the logic inside of that function. On the surface these seem to be equivalent in pretty much every scenario. I was wondering if anyone had any insight into whether one of these is better than the other? Or if I am missing another method that is better than these two?
Thanks!