Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Promises in JavaScript for Beginners
Shubh Sharma
Shubh Sharma

Posted on • Edited on

     

Promises in JavaScript for Beginners

Intro

When working with async code in javascript you sometimes need to wait for the code to return data before further processing of data.

For example: reading a file takes some times or fetching data from the server can take time and since this is async task it gets delegated.

However we need this data before we can process and do anything further in our code. This is where promises can be super helpful.

What is a Promise?

Before promises were introduced, managing asynchronous operations was done using callbacks.

Callbacks are functions that are passed as arguments to another function and are executed later, once the asynchronous operation is complete.

However, as programs grew in complexity, managing callbacks became challenging, leading to what's often referred to as "callback hell" or "pyramid of doom."

This is a situation where nested callbacks make the code hard to read and maintain.

Promises were introduced to address these issues and provide a better/cleaner way to handle asynchronous operations.

So what the heck is aPromise? well, a promise is an object representing the eventual completion or failure of an async operation and its resulting value.

In short if an async task is completed with success it returns a resolve object with the data and if the task fails it returns a reject object with an error. Promise ensures that once the operation is completed, you can do anything you wanted depending on the completion or failure of the operation.

States of a promise

A Promise has three states:

  1. pending: Promise is pending and its neither resolved nor resolved
  2. resolved: Once promise is resolved it returns data tothen() method
  3. rejected: Once promise is rejected the error is returned tocatch()

A basic example of a promise used:

// Creating a promiseletmyPromise=newPromise((resolve,reject)=>{// Simulating async operation using setTimeoutsetTimeout(()=>{letsuccess=true;if(success){resolve("Data fetched successfully");}else{reject("Error fetching data");}},2000);});
Enter fullscreen modeExit fullscreen mode

This piece of code means a new promise is created which does an async operation such assetTimeout() and once its completed it either resolves the promise which means success or it gets reject with an error.

Once created a promise you can consume that promise.

// Consuming the promisemyPromise.then((result)=>{console.log(result);}).catch((error)=>{console.error(error);})//default one, gets executed no matter resolve or reject.finally(()=>{});
Enter fullscreen modeExit fullscreen mode

If the promise is resolved then it is returned to.then() method of that promise, if promise is rejected then it gets returned to.catch() method.

In both the cases, you can do a task after the promise is completed.

How to handle data returned by the promise?

This can be done with the help of chaining of then() and catch()

Once the data is returned from theresolve you can get that data inthen() method and then return it into a newthen chain and then you can use that data and the error is caught bycatch() method.

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{}consterror=false;console.log("Async task completed!");//data returned with resolveif(error===false)resolve([1,2,3]);,1000);});//handling data with chaining of then() and catch()promise.then((data)=>{returndata;}).then((data)=>{console.log(data.splice(0,1));}).catch((err)=>{console.log(err);})
Enter fullscreen modeExit fullscreen mode

Top comments(5)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
oculus42 profile image
Samuel Rouse
Tech generalist specializing in UI development. UI Architect by day. Playing with JavaScript for over 25 years.
  • Location
    Maine
  • Pronouns
    he/him
  • Work
    UI Architect at Bottomline Technologies
  • Joined

Nice article! This is a solid introduction to promises.

However, there is an error in your last code example.

// argument "data" and return "response" don't matchpromise.then((data)=>{returnresponse;})
Enter fullscreen modeExit fullscreen mode

This should either receiveresponse as the argument, or returndata. Either way, if it returns the original value the entire.then() is not necessary.

If you are interested in some more suggestions for working with Promises, I wrote an article calledPromises: Five Tips to Work Smarter

CollapseExpand
 
shubhsharma19 profile image
Shubh Sharma
Self taught web developer and designer
  • Email
  • Location
    India
  • Education
    Master of Computer Applications
  • Pronouns
    He/They
  • Work
    Technical writer (Part-time)
  • Joined

Fixed it, thanks for the update! :)

CollapseExpand
 
corners2wall profile image
Corners 2 Wall
Average frontend developer
  • Joined

You inspired me to write an article. Thank you

CollapseExpand
 
shubhsharma19 profile image
Shubh Sharma
Self taught web developer and designer
  • Email
  • Location
    India
  • Education
    Master of Computer Applications
  • Pronouns
    He/They
  • Work
    Technical writer (Part-time)
  • Joined

Thankyou for reading! :)

CollapseExpand
 
Sloan, the sloth mascot
Comment deleted

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Self taught web developer and designer
  • Location
    India
  • Education
    Master of Computer Applications
  • Pronouns
    He/They
  • Work
    Technical writer (Part-time)
  • Joined

More fromShubh Sharma

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp