Explaining Constructing a promise in JavaScript as if You Were a Kid
In previous article, we understood the concept of promises using the example of Jeff asking his mom to bake a cake.
Now, let's see how to create promises.
To create a promise in JavaScript, we use the new Promise
constructor, which takes in a function containing two arguments: resolve
and reject
.
const promise = new Promise((resolve, reject) => { /* Do something here */ });
When resolve
is called within the function, the promise succeeds, and the execution continues into the .then
chain. Any parameter passed into resolve
becomes the argument for the next .then
call.
const promise = new Promise((resolve, reject) => { return resolve(27); }); promise.then((number) => console.log(number)); // Output: 27
Conversely, if reject
is called within the function, the promise fails, and the execution continues into the .catch
chain. Similarly, any parameter passed into reject
becomes the argument for the .catch
call.
const promise = new Promise((resolve, reject) => { return reject("Rejected"); }); promise.catch((err) => console.log(err)); // Output: Rejected
Now, let's apply this concept to mom's promise to bake a cake for Jeff.
const momBakesCake = (cakeType) => { return new Promise((resolve, reject) => { setTimeout(() => { if (cakeType === "black forest") { resolve("black forest cake!"); } else { reject("No cake đ˘"); } }, 1000); }); };
In this example, Mom promises to bake a cake of a specific type (cakeType
) after a certain period. If she bakes the requested cake, the promise is fulfilled (resolve
), and the cake type is passed to the next .then
call. Otherwise, if Mom bakes a different cake or no cake at all, the promise is rejected (reject
), and the appropriate message is passed to the .catch
call.
const promise = momBakesCake("black forest") .then((cake) => console.log(cake)) .catch((nocake) => console.log(nocake));
By logging the promise, we can see its status as pending initially. Upon execution, depending on Mom's baking, we'll either get the desired cake or a message indicating no cake.
I have created a set of resources for learning asynchronous JavaScript. These guidesâCallbacks, Promises, and Async/Await âcover everything Iâve learned from years of real-world JavaScript experience.
If you found this article helpful, youâll get so much out of these guides. Each one is optimized for those âlightbulb moments,â building a strong mental model for how asynchronous JavaScript works and how you can use it to create fast, dynamic applications.