Chances are that if you have ever used fetch()
to get some sort of a JSON hash back from an external API, such as fetching some important headlines from a respectable news site, (see screen cap below) you have been interacting with a Promise
object this whole time, and you are 70% of the way there in understanding what Promises are in JavaScript.
The Basics
In essence, a Promise in JavaScript is a lot like a promise made in real life. As promises in real life are either kept or broken, JavaScript Promises get either resolved or rejected.
To explore this further, let’s take a look at how a small child promising his parents to clean his room looks like in JavaScript.
In JavaScript, a Promise takes in two callbacks: resolve
and reject
. Reading through the above code, it is evident that our small child fulfilled his promise to clean his room. Therefore, our Promise object here— once called upon— will resolve
to return 'Clean'
as its response. Suppose our…