Shubham Ankit

Shubham Ankit

1561134356

Understanding Promises in JavaScript

Learn How Promises Really Work in JavaScript, to write better code - JavaScript is a single-threaded programming language, that means only one thing can happen at a time. Before ES6, we used callbacks to handle asynchronous tasks such as network requests.

Using promises, we can avoid the infamous ‘callback hell’ and make our code cleaner, easier to read, and easier to understand.

Suppose we want to get some data from a server asynchronously, using callbacks we would do something like this:

getData(function(x){
    console.log(x);
    getMoreData(x, function(y){
        console.log(y); 
        getSomeMoreData(y, function(z){ 
            console.log(z);
        });
    });
});

Here I am requesting some data from the server by calling the getData() function, which receives the data inside the callback function. Inside the callback function, I am requesting for some more data by calling the getMoreData()function passing the previously received data as an argument and so on.

This is what we call callback hell, where each callback is nested inside another callback, and each inner callback is dependent on its parent.

We can rewrite the above snippet using promises. For example:

getData()
  .then((x) => {
    console.log(x);
    return getMoreData(x);
  })
  .then((y) => {
    console.log(y);
    return getSomeMoreData(y);
  })
  .then((z) => {
    console.log(z);
   });

We can see that this is much cleaner and easier to understand than the callbacks example above it.

Suggestion: When build an app in JavaScript, you often have to rewrite the same components and pieces. Instead, share them as Bit components so you can later use, share and sync them in all your projects. Create a collection:

What is a Promise?

A Promise is an object that holds the future value of an async operation. For example, if we are requesting some data from a server, the promise promises us to get that data which we can use in future.

Before we get into all the technical stuff, let’s understand the terminology of a Promise.

States of a Promise

A Promise in JavaScript just like a promise in real-world has 3 states. It can be 1) unresolved (pending), 2) resolved (fulfilled), or 3) rejected. For example:

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • Resolved or Fulfilled — A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • Rejected — A Promise is rejected if an error happened.

Now that we know what a Promise is, and Promise terminology, let’s get back to the practical side of the Promises.

Creating a Promise

Most of the times you will be consuming promises rather than creating them, but it’s still important to know how to create them.

Syntax:

const promise = new Promise((resolve, reject) => {
    ...
  });

We create a new promise using the Promise constructor it takes a single argument, a callback, also known as executor function which takes two callbacks, resolve and reject.

The executor function is immediately executed when a promise is created. The promise is resolved by calling the resolve() and rejected by calling reject(). For example:

const promise = new Promise((resolve, reject) => {
  if(allWentWell) {
    resolve('All things went well!');
  } else {
    reject('Something went wrong');
  }
});

The resolve() and reject() takes one argument which can be a string, number, boolean, array or object.

Let’s look at another example to fully understand the promise creation.

const promise = new Promise((resolve, reject) => {
  const randomNumber = Math.random();
  setTimeout(() => {
    if(randomNumber < .6) {
      resolve('All things went well!');
    } else {
    reject('Something went wrong');
  }
  }, 2000);
});

Here I am creating a new promise using the Promise constructor. The promise is resolved or rejected after 2 seconds of its creation. The promise is resolved if the randomNumber is less than .6 and rejected otherwise.

When the promise is created, it will be in the pending state, and its value will be undefined. For example:

![javascript](https://cdn-images-1.medium.com/max/1600/1*ugVOwFz9–fp3vDgUd94Ug.png “javascript”)After the 2 seconds timer finishes, the promise is either resolved or rejected randomly, and its value will be the value passed to the resolve or reject function. For example:

**Note **— A promise can be resolved or rejected only once. Further invocation of resolve() or reject() has no effect on Promise state. For example:

const promise = new Promise((resolve, reject) => {
  resolve('Promise resolved');  // Promise is resolved
  reject('Promise rejected');   // Promise can't be rejected
});

Since resolve() is called first so the Promise will be resolved. Calling reject() after that will have no effect on the Promise state.

Consuming a Promise

Now that we know how to create a promise, let’s understand how to consume an already created promise. We consume a promise by calling then() and catch() methods on the promise.

For example, requesting data from an API using fetch which returns a promise.

**.then()** syntaxpromise.then(successCallback, failureCallback)

The successCallback is called when a promise is resolved. It takes one argument which is the value passed to resolve().

The failureCallback is called when a promise is rejected. It takes one argument which is the value passed to reject().

For example:

const promise = new Promise((resolve, reject) => {
  const randomNumber = Math.random();

  if(randomNumber < .7) {
    resolve('All things went well!');
  } else {
    reject(new Error('Something went wrong'));
  }
});
promise.then((data) => {
  console.log(data);  // prints 'All things went well!'
  },
  (error) => {
  console.log(error); // prints Error object
  }
);

Here if the promise is resolved, the successCallback is called with the value passed to resolve(). And if the promise is rejected, the failureCallback is called with the value passed to reject().

**.catch()** syntaxpromise.catch(failureCallback)

We use catch() for handling errors. It’s more readable than handling errors inside the failureCallback callback of the then() callback. For example:

const promise = new Promise((resolve, reject) => {
  reject(new Error('Something went wrong'));
});
promise
  .then((data) => {
     console.log(data);
   })
  .catch((error) => {
     console.log(error); // prints Error object
  });

Promise Chaining

The then() and catch() methods can also return a new promise which can be handled by chaining another then() at the end of the previous then() method.

We use promise chaining when we want to resolve promises in a sequence.

For example:

const promise1 = new Promise((resolve, reject) => {
  resolve('Promise1 resolved');
});
const promise2 = new Promise((resolve, reject) => {
  resolve('Promise2 resolved');
});
const promise3 = new Promise((resolve, reject) => {
  reject('Promise3 rejected');
});
promise1
  .then((data) => {
    console.log(data);  // Promise1 resolved
    return promise2;
  })
  .then((data) => {
    console.log(data);  // Promise2 resolved
    return promise3;
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);  // Promise3 rejected
  });

So what’s happening here?

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • Resolved or Fulfilled — A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • Rejected — A Promise is rejected if an error happened.

Note — Generally only one catch() is enough for handling rejection of any promise in the promise chain, if it’s at the end of the chain.

Common Mistake

A lot of beginners make the mistake of nesting promises inside another promise. For example:

const promise1 = new Promise((resolve, reject) => {
  resolve('Promise1 resolved');
});
const promise2 = new Promise((resolve, reject) => {
  resolve('Promise2 resolved');
});
const promise3 = new Promise((resolve, reject) => {
  reject('Promise3 rejected');
});
promise1.then((data) => {
  console.log(data);  // Promise1 resolved
  promise2.then((data) => {
    console.log(data);  // Promise2 resolved

    promise3.then((data) => {
      console.log(data);
    }).catch((error) => {
      console.log(error);  // Promise3 rejected
    });
  }).catch((error) => {
    console.log(error);
  })
}).catch((error) => {
    console.log(error);
  });

Although this works fine, this is considered to be a poor style and makes our code difficult to read. If you have a sequence of promises to resolve, it’s better to chain promises one after another rather than nest one inside another.

Promise.all( )

This method takes an array of promises as input and returns a new promise that fulfills when all of the promises inside the input array have fulfilled or rejects as soon as one of the promises in the array rejects. For example:

const promise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise1 resolved');
 }, 2000);
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise2 resolved');
 }, 1500);
});
Promise.all([promise1, promise2])
  .then((data) => console.log(data[0], data[1]))
  .catch((error) => console.log(error));

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • Resolved or Fulfilled — A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • Rejected — A Promise is rejected if an error happened.
const promise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise1 resolved');
 }, 2000);
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(() => {
  reject('Promise2 rejected');
 }, 1500);
});
Promise.all([promise1, promise2])
  .then((data) => console.log(data[0], data[1]))
  .catch((error) => console.log(error));  // Promise2 rejected

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • Resolved or Fulfilled — A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • Rejected — A Promise is rejected if an error happened.

This method can be useful when you have more than one promise, and you want to know when all of the promises have resolved. For example, if you are requesting data from different APIs and you want to do something with the data only when all of the requests are successful.

So Promise.all() waits for all promises to succeed and fails if any of the promises in the array fails.

Promise.race( )

This method takes an array of promises as input and returns a new promise that fulfills as soon as one of the promises in the input array fulfills or rejects as soon as one of the promises in the input array rejects. For example:

const promise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise1 resolved');
 }, 1000);
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(() => {
  reject('Promise2 rejected');
 }, 1500);
});
Promise.race([promise1, promise2])
  .then((data) => console.log(data))  // Promise1 resolved
  .catch((error) => console.log(error));

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • Resolved or Fulfilled — A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • Rejected — A Promise is rejected if an error happened.

So Promise.race() waits for one of the promises in the array to succeed or fail and fulfills or rejects as soon as one of the promises in the array is resolved or rejected.

Conclusion

We have learned what promises are and how to use them in JavaScript. A Promise has two parts 1) Promise creation and 2) consuming a Promise. Most of the times you will be consuming promises rather than creating them, but it’s still important to know how to create them.

That’s it and hope you found this article helpful! Please feel free to comment below and ask anything, suggest feedback or just chat. Cheers! ⭐️

#javascript

What is GEEK

Buddha Community

Understanding Promises in JavaScript
Julie  Donnelly

Julie Donnelly

1602406920

JavaScript Promise: Methods Comparison

Introduction

Promises in JavaScript are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that certain event has taken place, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected. They can handle multiple asynchronous operations easily and they provide better error handling than callbacks and events.

Callback: A callback is a function that is passed into another function as an argument to be executed later.

Events: Events provide a dynamic interface to a WebPage and are connected to elements in the Document Object Model(DOM), for example: onclick(), onmouseover() etc.

A Promise has four states

Pending: Before the event has happened, the promise is in the pending state.

Settled: Once the event has happened it is then in the settled state.

Fulfilled: Action related to the promise has succeeded.

Rejected: Action related to the promise has failed.

#javascript #javascript-development #javascript-tutorial #promises #javascript-tips

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()

https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html

#javascript #promise.all #promise.allsettled #ecma #promise #jquery

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hugo JS

Hugo JS

1599295469

What is Callback-Function in JavaScript? How it is Replaced By Promises?

Let us understand term _Callback _by an real-world example: Suppose, you are calling to your Girlfriend (If you have) and she is busy in another call then she send message to you : “I am busy right now, Call back you later.!!”. After completing her work, she calls you back and this is what call back in JavaScript as well.

In JavaScript, When a function is executing (Girlfriend is talking with someone) then after function execution is completed another function is started for execution this is call back function.

Now you are thinking that its depend upon when, where you are calling function and all function call is “Call-back function”. Image for post

Here, _printWorld() _function is executed after _printHello() _complete its execution but this is not call-back function example because _printHello() _is not Asynchronous function. Suppose, _printHello() _prints after 1 Second then _printWorld() _executes first.

Image for post

What if we want “Hello World” output when Asynchronous function is there. We can pass function as argument and calls it after _printHello() _complete its execution. Here below code snippet of how _function pass as argument _:

Image for post

Callback function can be defined as a function passed by argument and executes when one function completes its execution.

Suppose, If you have API (Application Programming Interface) to get Students Roll numbers and select one of Roll number — getting that roll number’s data and print that data. We don’t have API to get students data so we are using _setTimeout() _Async function and getting roll number after 2s, We are also selecting one of roll number manually after 2s and print Roll number’s data after 2s. This can be done by call back function.

Image for post

The program became complex and complex if we have too many things to do like Getting Students data, Selecting one of them student, get student’s roll number and get result by roll number then it become very complex. If you have any Error in this then debugging is also tedious task, this things is called “Callback Hell”, which is shape like “Pyramid Of Doom”.

To overcome with this problem, Promises is introduced in JavaScript. Promises has three states : Pending, Resolved, Reject. Promises is created by Constructor : new Promise(). It has one executor function which has two arguments (resolve, reject).

Promise object has three methods: then(), catch() & finally().

Image for post

If Promise is successfully executed then its data is transferred through resolve function and if it has error then passed through reject function.

We have implemented same task which is done using call back function in Promises and its easily understandable However it is complicated compare to callback function but when you use promises for sometimes then it’s easy to implement.

In _getRollNumber(), _resolve method’s data is caught by then() functions arguments and reject method’s data is caught by catch() function. Here In Promises, Every task has different promises because of that it is easy to debug and readable compare to call back function. You can see that there is no shape like “Pyramid of Doom” in Promises. This is how Callback function is replaced by Promises.

Thank you for reading!

This article was originally published on Medium.com

#javascript-tips #advanced-javascript #javascript #callback-function #promises