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 1237

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

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T06:16:08+00:00 2024-11-25T06:16:08+00:00

All in one! JavaScript promises…

  • 62k

Okay! So before starting we’ll make a promise to each other 😅
My Promise: I’ll try to explain Javascript Promises, in the best way possible!
Your Promise: Read the complete blog! 😃

For now, both of our promises are in a pending state, let’s try to get them fulfilled 🙈

Okay, We’ll start with a small introduction of asynchronous JS…
A promise is a method that eventually produces value. It can be considered as the asynchronous counterpart of a getter function. Its essence can be explained as:

promise.then(function(value) {   // Do something with the 'value' }); 
Enter fullscreen mode Exit fullscreen mode

We know that Javascript is single-threaded & Only one thing can happen at a time, on a single main thread, and everything else is blocked until an operation is complete. So, Suppose if you want to fetch data from the network or database, the main thread will get blocked and how much time it will take to complete we don’t know.
Hence, to solve this problem we have two main types of asynchronous code style:

  1. Old-style callbacks

  2. Newer promise-style code

We’ll explore each one of it!

let promise = new Promise(function(resolve, reject){    // executor (the producing code, "singer")  }); 
Enter fullscreen mode Exit fullscreen mode

The function passed to the new Promise is called the executor. When a new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result.

Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the executor. When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:

  • resolve(value) — if the job is finished successfully, with result value.

  • reject(error) — if an error has occurred, an error is the error object.

Promise Chaining

If we want to execute two or more asynchronous operations back to back, where each requires a previous operation result then chaining comes in!

chooseProduct() .then(up => selectProduct(up)) .then(cart=> addToCart(cart)) .then(buy=> buyProduct(buy)) .catch(failureCallback); 
Enter fullscreen mode Exit fullscreen mode

To avoid promise chaining and to write clean code, we have async & await. Async Await acts as syntactic sugar on top of promises, making asynchronous code easier to write and read!

const readData = async() => {  try{      const response = await fetch(URL);      console.log(response);   }  catch(err){     console.log(err);   } } 
Enter fullscreen mode Exit fullscreen mode

There are some static methods of promises in javascript..

  • Promise.all(iterable)

  • Promise.race(iterable)

  • Promise.reject(reason)

  • Promise.resolve(value)

    Promise.all()

Promise.all() method takes an iterable of promises as an input and returns a single Promise that resolves to an array of the results of the input promises. It rejects immediately upon any of the input promises rejects.

p1 = Promise.resolve(50); p2 = 200 p3 = new Promise(function(resolve, reject) {    setTimeout(resolve, 100, 'geek'); });  Promise.all([p1, p2, p3]).then(function(values) {     document.write(values); }); 
Enter fullscreen mode Exit fullscreen mode

Promise.race()

The Promise.race() static method accepts a list of promises as an iterable object and returns a new promise that fulfills or rejects as soon as there is one promise that fulfills or rejects, with the value or reason from that promise.

const p1 = new Promise((resolve, reject) => {     setTimeout(() => {         console.log('The first promise has resolved');         resolve(10);     }, 1 * 1000);  });  const p2 = new Promise((resolve, reject) => {     setTimeout(() => {         console.log('The second promise has resolved');         resolve(20);     }, 2 * 1000); });  Promise.race([p1, p2])     .then(value => console.log(`Resolved: ${value}`))     .catch(reason => console.log(`Rejected: ${reason}`));  //OUTPUT The first promise has resolved  Resolved: 10  The second promise has resolved 
Enter fullscreen mode Exit fullscreen mode

The following example creates two promises. The first promise resolves in 1 second while the second one rejects in 2 seconds. Because the first promise is faster than the second one, the returned promise resolves to the value from the first promise.

There are some instance Methods of Promise in javascript..

  • Promise.prototype.then()

  • Promise.prototype.catch()

  • Promise.prototype.finally()

congratulations!!

Finally, we reached our destination. Since you are here, you fulfilled your promise and I hope I was able to keep mine too.

Hope you enjoyed and learned something new! Bye 👋

  • Bhavy Kapadia(Programmer Analyst) at DhiWise

javascriptprogrammingtutorialwebdev
  • 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.