Javascript Promise Function Style -


suppose have function return promise based on input value need calculated first. seems there 2 ways 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 of setup outside of promise function. , second moves of logic inside of function. on surface these seem equivalent in pretty every scenario. wondering if had insight whether 1 of these better other? or if missing method better these two?

thanks!

the difference between 2 functions variables initialised, difference being variable scope. 2 functions both return same result promise, first approach has benefit of being able access variables within function, while outside of promise.

variables outside promise:

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);  });

variables inside promise:

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);  });

as such, depends on how want use variables. if you'd utilise them outside of promise, opt first of 2 functions. if know you're never going need access variables outside of promise, define them within promise prevent variable scope leaking, in turn improving memory.

hope helps! :)


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -