Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6574

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T07:48:07+00:00 2024-11-27T07:48:07+00:00

Promises in JavaScript for Beginners

  • 60k

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 a Promise? 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 to then() method
  3. rejected: Once promise is rejected the error is returned to catch()

A basic example of a promise used:

// Creating a promise  let myPromise = new Promise((resolve, reject) => {     // Simulating async operation using setTimeout     setTimeout(() => {         let success = true;         if (success) {             resolve("Data fetched successfully");         } else {             reject("Error fetching data");         }     }, 2000); }); 
Enter fullscreen mode Exit fullscreen mode

This piece of code means a new promise is created which does an async operation such as setTimeout() 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 promise myPromise .then((result) => {     console.log(result); }) .catch((error) => {   console.error(error); }) //default one, gets executed no matter resolve or reject .finally(() => {}); 
Enter fullscreen mode Exit 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 the resolve you can get that data in then() method and then return it into a new then chain and then you can use that data and the error is caught by catch() method.

const promise = new Promise((resolve, reject) => {     setTimeout(() => {}        const error = false;         console.log("Async task completed!");         //data returned with resolve         if(error === false) resolve([1,2,3]); , 1000); });  //handling data with chaining of then() and catch() promise.then((data) => {     return data; }) .then((data) => {     console.log(data.splice(0, 1)); }) .catch((err) => {     console.log(err); }) 
Enter fullscreen mode Exit fullscreen mode

beginnersjavascriptpromiseswebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.