Skip to content
Advertisement

Understanding Promises in Javascript

I was trying to comprehend the use of Promise in Javascript for which Google search lead me to this article

The author of post points out this

Promises (like callbacks) allow us to wait on certain code to finish execution prior to running the next bit of code.

Which for some reason sounded like this to me (and it porbably might be)

  axios.get(url).then((response) => ).catch((err) => 

Thereafter he showed this example

function delay(t){
  return new Promise(function(resolve){
    return setTimeout(resolve, t)
  });
}
function logHi(){
  console.log('hi');
}
delay(2000).then(logHi);

Here, I am unable to comprehend what/how are we passing something in resolve here function(resolve) and when do we use something like

 return new Promise(function(resolve){

and when do we do something like

  axios.get(url).then((response) => ).catch((err) => 

Advertisement

Answer

The example code isn’t great because the promise doesn’t actually resolve a value — so nothing is passed to the then(). The function passed to then isn’t expecting a value either. It’s just waiting and logging ‘hi’. So basically it’s a timer with no resolved values.

If you want values passed around, you need to resolve and actual value:

It would be a more instructive example if they returned a value and then explicitly used that value. Something more like:

function delay(t) {
  return new Promise(function(resolve) {
    return setTimeout(() => resolve("some value from promise"), t)
  });
}

function logHi(text) {
  console.log(text);
}
delay(1000).then(logHi)
// alternatively the same result as:
// delay(1000).then(value => logHi(value));

The code above uses a promise that we manually created because we wanted to resolve something after setTimeout which does not return a promise of it’s own. It essentially promisifies setTimeout. When you use a library like axios, it’s get method already returns a promise, so you can just use it like:

 axios.get(url).then((response) => )

There’s no need (and in fact it’s an anti-pattern) to wrap it in another new Promise. You can just take the promise returned from get() and call then() on that promise.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement