Molasses
Molasses

Reputation: 699

What is happening in this TypeScript code snippet?

I'm fairly new to TypeScript, but have used JavaScript. I'm learning TypeScript for the purpose of using Angular 2. During one of my tutorials, I ran into this bit of code...

return new Promise(resolve => {
  // Simulate server latency with 2 second delay
  setTimeout(() => resolve(this.getHeroes()), 2000);
});

I only read a little bit on the Promise class, but it seems like it contains a resolve method. So, I'm trying to figure out the data flow of what's actually happening in that code snippet above. A Promise class is instantiated with an argument of a resolve variable that holds a method? I guess I'm a little confused because of that second resolve word in the code. If that's the same resolve that's part of the Promise class, then how is it already getting called before the Promise object is even instantiated. Unless resolve is somehow a static method?

Basically, I'm trying to figure what the heck is going on in that return statement...

Mahalo in advance!

Upvotes: 2

Views: 396

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40936

The promise object constructor accepts two arguments:

  • resolve : a method that should be called when you want the promise to emit the result of its work (eg: return data from an HTTP call)

  • reject: a method that should be called when you want the promise to emit an error.

These two arguments match up with the two ways a promise can end up. The code snippet you gave ignores the second argument, so this promise never emits an error. Let's look more closely at what we do have:

setTimeout(() => resolve(this.getHeroes()), 2000);

setTimeout takes two arguments

  • callback: the function to execute in the future

  • delay: how long to wait before executing

In your case, after 2000 milliseconds, () => resolve(this.getHeroes()) will be executed. This is a function with no argument () and whose body has just one line of code:

resolve(this.getHeroes())

So basically, in 2 seconds, the promise will resolve by emitting the result of the getHeroes() method. Whichever code called the function that returned the promise will get the heroes at that time. In the example below, someFunction is the one that actually has return new Promise(...) and result is the output of getHeroes()

someFunction().then(result => this.heroes = result)

Upvotes: 3

Related Questions