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.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices ā as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. Iām really benefiting from the valuable insights and tips you share.