DEV Community

Smriti
Smriti

Posted on Edited on

A Beginner's Guide to Promises in JavaScript (with Real Examples)

What is a Promise?
A Promise is just a way for JavaScript to handle asynchronous operations - things that take time
like:

  • Fetching data from a server
  • Reading a file
  • Waiting for a timeout Instead of blocking everything, JavaScript says: "Hey! I'll do this task, and when I'm done, I'll let you know." A Promise can be in 3 states:
  • Pending - task is not done yet
  • Resolved - task completed successfully
  • Rejected - task failed

Basic Syntax of a Promise

const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task done!");
} else {
reject("Something went wrong.");
}
});
promise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

Real Example: Fake API Call

function fakeAPICall() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
fakeAPICall()
.then(data => console.log(data))
.catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

Output after 2 seconds: Data received!

Chaining Promises
doSomething()
.then(result1 => doSomethingElse(result1))
.then(result2 => doMore(result2))
.catch(error => console.log(error));

My Personal Tip
Think of them like a food delivery app:

  • You order (async task starts)
  • You get food (resolve)
  • Or delivery fails (reject) And .then() is what you do when food arrives

Resources That Helped Me

  • MDN Web Docs - Promises
  • JavaScript.info - Promises

Final Thoughts
At first, I used to avoid Promises. But once I started coding with real APIs in React, I had to learn
them - and I'm glad I did.
If you're new to Promises, I hope this helped you simplify the concept!
Drop a comment if you found this helpful or if you want me to write about async/await next!
Thanks for reading!
Follow me on Dev.to - this is just the start of my blog journey

Top comments (2)

Collapse
 
armando_ota profile image
Armando Ota •

Heres another tip:
When you order from different food deliveries for food event and you need to serve them when all arrive

function getFoodDelivery1(foodList1) {
    let promise = new Promise();
    //
    // do async stuff
    // 
    return promise;
}


function getFoodDelivery2(foodList2) {
    let promise = new Promise();
    //
    // do async stuff
    // 
    return promise;
}


function loadCatalog() {
    let foodList1 = { ... };
    let foodList2 = { ... };

    // when you need executed methods with extra params ;)
    let loadCatalogSequence = [
        () => getFoodDelivery1(foodList1),
        () => getFoodDelivery2(foodList2)
    ];

    Promise.all((loadCatalogSequence).then((deliveredFood) => { //or allSetteled()

        // check delivered food 

    });

}
Enter fullscreen mode Exit fullscreen mode

Dislaimer: do not copy this code ... it's for reference only !

Collapse
 
nevodavid profile image
Nevo David •

pretty cool seeing you stick with stuff that’s tough at first. you ever feel like it’s all about just showing up every day till it finally clicks?