This page looks best with JavaScript enabled

Beginner's Introduction to Promises in JavaScript

 ·   ·  β˜• 2 min read

Introduction

Promise is a language feature for asynchronous programming in JavaScript.

As JavaScript is single threaded, if you are doing something which waits for I/O, you create a Promise for that task. This task could be waiting for an API call from Twitter for example, or reading a file from a filesystem), and you let it run without getting in the way of normal execution flow.

The Promise at a later time either gets fulfilled (successful), also known as resolved in JS terminology or gets failed, also known as rejected in JS terminology.

Let us understand it with an example. Below function returns a Promise.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function doSomething(msg) {
  return new Promise(=> (resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("It worked!");
  }
  else {
    reject("It failed");
  }
})

Now Promises have some methods attached to them which are useful when you want to run a block of code (callback function) when Promise either gets resolved or rejected. In code we would write something like this:

1
2
3
4
doSomething("1st Call")
  .then(() => doSomething("2nd Call"))
  .then(() => doSomething("3rd Call"))
  .catch(err => console.error(err.message));

Although you can have a catch at an intermediate position, one should keep it at last because it will show all the rejections at one same place, if there are more than one.

Share on

Santosh Kumar
WRITTEN BY
Santosh Kumar
Fullstack Developer at Method Studios