Suppose I have a function that returns a promise based on some input value that needs to be calculated first. There seem to be 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);
});
Run codeHide resultExample 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);
});
Run codeHide resultIn the first example, the entire setting is saved outside the promise function. And the second moves all the logic inside this function. At first glance, they seem equivalent in almost all scenarios. I was wondering if anyone has an idea whether one of them is better than the other? Or if I miss another method that is better than the two?
Thank!
source
share