Could you help me understand Promises?

Could you help me understand Promises?
0

#1

Hello there!

So, my main question is, what is a “Promise” and when do we use them?
When we’re using fetch(), the response is a Promise because the request may take some time or…?

Thanks.


#2

pretty much, we use promises when we have to wait for an action to complete. So something like:

fetch('/some/api')
  .then(response => { // do something with response };

#3

Promises are a better approach to dealing with asynchronous code. When created, promises are pending some task, and once the task is done, they are either resolved with a value if the task executes correctly, or they are rejected with an error.

You use them when you have an asynchronous task or event and want to run code after it is completed. In the past, callbacks were the normal approach. For example:

getData(theDataIWant, function(data) {
  // do something
  handleData(function() {
    // do something else
  })
});

Callbacks are bad for a number of reasons. Promises were created to make an easier to use interface for dealing with asynchronous code like this. With promises, we could simplify the above like this:

getData(dataIWant)
  .then(data => {
    // do something
  })
  .then(newData => {
    // do something else
  })

Promises let us break complex asynchronous tasks into more readable pseudo-synchronous tasks. They can do a lot more, but that is Promises in a nutshell. Now regarding fetch, fetch takes time to get data from a server. It’s like jQuery’s $.getJSON() which runs a callback once the value returns. Fetch is pretty easy to use for simple GET requests, but since GETTING data from a server is an asynchronous task, fetch must return a Promise or require a callback. Since fetch returns a promise, we can handle it like @nikrb stated above.

Now, Promises were really an improvement, but they had some flaws. Another utility was built on top of Promises called Async Functions. Basically, they allow us to await a Promise. Usage with fetch would be like this:

async function getData() {
  let res = await fetch('www.url.com/api')
  let json = await res.json()
  
  // do something with the JSON data we have received.
}

So, use Promises and use Async functions too. Async functions won’t replace Promises, and require knowledge of Promises to work correctly.

Async functions and Promises are standard in modern browsers, so you don’t need to worry about using Babel or anything. Should work out of the box for you.

Here are some articles you should definitely read: