0

Does a fixed parameter, one that does not change once it is passed to a function, stay in scope for promise calls within the function. For example, can I trust x in the function below?

someFunc(1);
someFunc(2);

function someFunc(x){
    somePrmsFunc.then(function(){
        somePrmsFunc.then(function(){
            if (x == 1)
                alert(x);
        });
    });
}
Mark A. Rupert
  • 527
  • 7
  • 15
  • 1
    since `x` is not an object, yes you can trust `x` – Azad Mar 01 '19 at 05:09
  • 1
    Yes, since the parameter doesn't get reassigned, if it's a primitive, it will always be the same on the initial call as on any asynchronous call inside the `someFunc`. (If it were an object, it might get externally mutated in the meantime) – CertainPerformance Mar 01 '19 at 05:10

1 Answers1

2

since x is not an object, yes you can trust x

function somePrmsFunc() {

  return new Promise(function(resolve, reject) {

    setTimeout(resolve, 1000);
  });
}

function someFunc(x) {
  somePrmsFunc().then(function() {

    console.log('promise 1 resolved', x);
    somePrmsFunc().then(function() {
      console.log('nested promise resolved', x);
      if (x == 1)
        alert(x);
    });
  });
}

someFunc(1);
someFunc(2);
Azad
  • 5,144
  • 4
  • 28
  • 56