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?
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.