Promises in Javascript

During my last project review at Flatiron School, the instructor wasn’t fully convinced of my understanding of promises in Javascript. It is a very important concept in Javascript which is why I decided to write a blog about it.

What is a promise?

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

Promise Object Properties

  • While a Promise object is “pending” (working), the result is undefined.
  • When a Promise object is “fulfilled”, the result is a value.
  • When a Promise object is “rejected”, the result is an error object.

How Promise work?

How do I access the data in a promise?

Promise.then() takes two arguments, a callback for success and another for failure.

Both are optional, so you can add a callback for success or failure only.

How do I catch the errors from a promise chain?

Using the above example, this would look like this:

function deleteRestaurant(e) {
...
renderRestaurants()
})
.catch(err => { console.log(err) });
}

Async/Await

  • Async/await is a new way to write asynchronous code. Previous alternatives for asynchronous code are callbacks and promises.
  • Async/await is actually just syntax sugar built on top of promises. It cannot be used with plain callbacks or node callbacks.
  • Async/await is, like promises, non blocking.
  • Async/await makes asynchronous code look and behave a little more like synchronous code. This is where all its power lies.

This is how you would implement it using promises

And this is how it looks with async/await

The await keyword can only be used inside functions defined with async. Any async function returns a promise implicitly, and the resolve value of the promise will be whatever you return from the function (which is the string "done" in this case). await getJSON() means that the console.log call will wait until getJSON() promise resolves and print it value.

Why Is It better?

French guy who recently moved to the United States. I am also changing career after having worked 13 years in restaurants. I will be going into coding.