Is it possible to assign promise data value to outside variable?


#1

Is it possible to assign promise data value to outside variable?

I want to do something like:

var variable;

someFunction(){
  Promise.all([this.getReports(), this.getUser()]).then(data => {
    console.log("reports:    ", data[0]);
    console.log("user:    ", data[1]);
    this.variable = data[0]; // many to assign o variable
  })
}

In this example, I get variable undefined.

Are those two functions ([this.getReports(), this.getUser()]).) called synchronously?

I’m new to this, many thanks!


#2

variable will not be defined until the promises resolve, and generally speaking the only way to know when that is is to only access it from within the then clause. If you can’t do that (such as when it needs to be referenced from a template), it’s generally easiest to initialize it to a dummy value first.

I’m not quite sure what you’re asking, but if you mean “can I be certain that getReports has finished before getUser starts?”, the answer is no. You can be certain that both have finished by the time you are in the then.


#3

I see. But in this example I am assigning variable from then clause. And still getting the same undefined?


#4

I spoke earlier about how variable will be undefined until the promise resolves. If you are trying to use the value in any situation that may be earlier, you will be disappointed. Either ensure that that never happens (which is harder than you think, and probably not what your users want), or give it a dummy value earlier.


#5

what do you mean by dummy value? how would that help if I don’t need the dummy value and need the data[0]?

do you think something like this would work?

 Promise.all([this.getReports(), this.getUser()]).then(data => {
    console.log("reports:    ", data[0]);
    console.log("user:    ", data[1]);
    return data[0]; // many to assign o variable
  }).then(var =>{
   this.variable = var;
  //do something with variable
})

Sorry for the confusion, I’m just trying to understand.


#6

Hi @vikneke,

Promises are asynchronous, meaning that the code above is not guaranteed (nor expected) to execute every line immediately after the previous.

This StackOverflow topic will explain the problem and multiple solutions in great detail.

Thanks,
Ryan


#7

By the way, this is a “dummy” value…

let serverName: string = "still discovering servers on the network...";
serverName = TimeConsumingDiscoveryForMyServer();

…you’re purposefully assigning an incorrect value to a variable. It’s obvious that it’s wrong, but you’re expecting your code to step in and later assign a proper value.

In Angular, you often see “loading…” or something of the sort used as “dummy” values.