af costa
af costa

Reputation: 296

Hard time understanding difference between Promise.resolve() and promise chain

I have some hard time understanding what is the difference between using Promise.resolve() and simple using the promise.

The explanation seems a bit hard to get so i have a little example:

For example, i have a method that return a promise like this:

requestPokemon() {
  return new Promise((resolve, reject) => {
    axios.get("https://pokeapi.co/api/v2/pokemon/1").then(value => {
      resolve(value);
    })
    .catch(error => {
      reject(error);
    })
  });
}

so, now i can call this method and chain the promise, i figure two ways of do it, and can't get it when Promise.resolve is better or not, my issue is understanding that.

so i solved it in two ways:

first:

Promise.resolve(this.requestPokemon()).then(value => {
  this.pokemon = value.data.name;
}).catch(error => {
  console.log(error);
})

second:

this.requestPokemon().then(value => {
  this.pokemon = value.data.name;
}).catch(error => {
  console.log(error);
})

please i need a little explanation of the downsides and upsides on doing it one way above the other, i appreciate the help a lot.

Thanks

Upvotes: 1

Views: 83

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

At first you dont need to construct a promise (thats an antipattern) in your requestPromise, just return the one from axios:

  requestPokemon() {
    return axios.get("https://pokeapi.co/api/v2/pokemon/1");
 }

Now lets have a look at this line:

 Promise.resolve(this.requestPokemon()).then(/*...*/)

It will create a new promise, that resolves or rejects when the axios promise resolves or rejects and adds a then handler to it. So it will be chained like this like this:

 resolve() -> Promise (axios) -> Promise (Promise.resolve) -> then
 reject() -> Promise (axios) -> Promise (Promise.resolve) -> catch

So as you can see Promise.resolve just passes through the data, so actually it is superflous. We actually just need:

 resolve() -> Promise (axios) -> then
 reject() -> Promise (axios) -> catch

Which can be done with:

 this.requestPokemon().then(/*...*/, /*...*/);

please i need a little explanation of the downsides and upsides on doing it one way above the other

Adding Promise.resolve is just a bit more typing and makes it less readable, there is no syntactical difference.

Upvotes: 3

Related Questions