Javascript promise function style

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 result

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);
});
Run codeHide result

In 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!

+4
source share
2 answers

, , , . , first , .

:

function foo(val) {
  var newVal = val + 100;
  var anotherVal = newVal % 12;
  var returnVal = anotherVal * 3;

  console.log(returnVal); // Returns 6

  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(returnVal);
    }, 1000);      
  });
}

foo(10).then(function(val) {
  console.log(val);
});
Hide result

:

function foo(val) {
  
  console.log(returnVal); // Variable doesn't exist
  
  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);
});
Hide result

, , . , first . , Promise, Promise , .

, !:)

+4

, Promise , UnhandledPromiseRejectionWarning, , , .

+1

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


All Articles