Promises in Javascript

Adnan Ahmed
4 min readDec 17, 2020

Handling asynchronous tasks in web development is very common. One way to handle this is through promises.

Let’s say that we have the following code in that we are running multiple print commands

console.log('step 1'); 
console.log('step 2');
console.log('step 3');
console.log('step 4');
console.log('step 5');
console.log('step 6');
console.log('step 7');
console.log('step 8');

The way the javascript interpreter works is that it runs the code line by line. And in the above example if any of the steps is taking an abnormal amount of time then javascript will wait for that step to finish before moving on to the next step. Now let’s say step 5 is taking 10 minutes to finish then our application will be stuck for 10 minutes before moving on to the next step.

Now here come the promises. Promises allow you to write asynchronous code. In which the javascript does not wait to complete that operation, rather, simply place it in the queue and cater to it from time to time, until it is completed.

How to create promise?

To create a promise we use the built-in javascript promise constructor. So let’s create a promise.

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

--

--

Adnan Ahmed

A software engineer sharing insights and experiences through blog posts. Delving into technical topics and occasional general musings. https://adnanahmed.info