What are promises, and when should I use them?


Lately I have been doing some projects and now I’m going to do a random quote generator using an API. I suppose that I should use promises with the API, but I still haven’t understood clearly what promises are, and how they work in JS code. Is there anyone that could explain me the concept of promises?

Basic concept is this:

When page is loading and it is making some API call, it has no idea how long will it take to get any data from that API.
There may be no data at all.

Should loading page wait? If so, how long?
Should it cancel loading completely and throw an error?
Should it load without the data?

Promises are trying to solve this problem by saying “let the page load without the data, and when the data will be available, it will be displayed”.

More info.

Right, just to add onto MTN’s answer.

The best explanation I’ve heard is talking about “now” and “later”. JS deals with things that are happening “now” and does not naturally wait for anything. (This is different than many other languages.)

JavasScript, because it is on the web, has to deal with a lot of “later” things. When you call an API, you don’t know when it will return: A millisecond? 17 seconds? 2.7 years? We don’t know, but we know that it is not “now”. JavaScript will not wait so we have to have someway to tell it what to do when the API call gets done.

One way to handle this is with a callback function. You probably learned this originally. The promise is an attempt for a cleaner solution. Later you will learn about async/await, which is an attempt to make promises prettier. To some extent, things like generator functions can be used for async too (like in Redux Sagas).

When should you use them? When the data isn’t being returned “now”. That is an oversimplification, but that is the basic idea.