AndreaNobili
AndreaNobili

Reputation: 43047

How exactly does this promise example work?

I am studying Angular 2 and I have a doubt with this code I found in a tutorial:

  appStatus = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('stable');
    }, 2000);
  });

I understood that this instruction does something like this: set the value of the appStatus variable to the string 'stable' after that 2 seconds are passed. Is this it?

But what exactly is a Promise? So the appStatus variable contains a Promise object reference that I think will contain the 'stable' resolved value after that 2 seconds are passed. But what exactly is and what contains?

What is the common use case of Promise?

Upvotes: 0

Views: 53

Answers (2)

towc
towc

Reputation: 2034

Promises are used in a lot of facets of JS, angular is a minor example. Long story short, Promises are .thenable objects. If you've ever worked with, for example, xhr (XMLHttpRequest), you can think of the .then(x) to act similarly to the xhr.onload = x, but this construct allows for much more powerful code. These two pieces of code act in very much the same way:

// callback "format"
const xhr = new XMLHttpRequest;
xhr.open('GET', '/api/some-query');
xhr.onload = () => { console.log(xhr.response); };
xhr.send();

// promise "format"
const xhrPromise = new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest;
  xhr.open('GET', '/api/some-query');
  // bad error handling, but proves the point
  xhr.onload = () => { resolve(xhr.response); };
  xhr.send();
});
xhrPromise.then((text) => { console.log(text); });

What you have up there is using the promise pattern. To make it easier to understand, here's a similar piece using the callback pattern:

setTimeout(() => { f('stable') }, 2000);

this is assuming you append this to your current code:

appStatus.then((status) => { f(status) });

How this can be a lot better may not be clear at first, but once you delve into it and discover that promises are chainable (appStatus.then(...).then(...)), how error handling works with .catch and similar, it's easy to fall in love with them

There are plenty of good reads to understand how promises work, like the MDN docs and this post by Jake Archibald

Upvotes: 1

Faly
Faly

Reputation: 13356

appStatus value will not be the string 'stable' as you think. appStatus value is here a promise object that promises you the string 'stable' (you will get it after 2 seconds). To get the value 'stable' from the promise (you'll get it when the 2 seconds duration ends), you have to do:

appStatus.then((result) => { console.log(result); });

Upvotes: 3

Related Questions