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)

JavaScript

Thereafter he showed this example

JavaScript

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

JavaScript

and when do we do something like

JavaScript

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:

JavaScript

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:

JavaScript

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