How to Promise

First published: 2016-01-05      |      Last updated: 2025-06-25

As a front-end developer, if you haven't heard about Promise in Javascript, well ...
At least you have heard about it now! And it is truly amazing.

Promise is a the standard way of handling asynchronous operations, such as calling APIs. It is comprehensive but elegant, espeically with a series of Async operations and handling the errors from them.
It has been widely supported by mordern browsers. But of course IE is not one of the modern ones, so do not forget to find a promise-polyfill for your IE users.

Can I use Promise
Polyfill for IE

In this blog I will cover the basic usages for Promise, let's get started.
A promise function would look like this

1new Promise(function (resolve, reject) {
2    var data = asyncCall(); // could be API calls
3    if( data ) {
4        resolve(data); // success
5    } else {
6        reject(data); // fail
7    }
8});

First we need to declare it is a `new` Promise, inside you can put your async calls and let promise know how to deal with the response with `resolve` and `reject`. You can treat `resolve` and `reject` as two callback functions, `resolve` when you are confirmed that you have got what you expect, and reject if anything bad happened.

Here is a brief example, Fiddle it here

1var aync1 = function() {
2    return new Promise(function(resolve, reject){
3        // Wait 1s and alert
4        setTimeout(function(){
5            resolve("Hello Promise");
6        }, 1000);
7    });
8}
9aync1().then(function (resp) {
10alert(resp);
11});

If something is going wrong, you want to catch and handle it, Fiddle it here.

1var aync2 = function() {
2    return new Promise(function(resolve, reject){
3        // Wait 2s and alert
4        setTimeout(function(){
5            // pretend we got something wrong.
6            reject("error");
7        }, 1000);
8    });
9}
10aync2().then(function (resp) {
11alert("This will not be called");
12}).catch(function(err){
13alert(err);
14});

Here I have quickly demonstrated the basic usage of Promise, you may think "Oh callbacks can do the same thing as well". You are not wrong, but in next blog I will show the real power of Promise, thanks for reading.

Solomon Yu
By Solomon YuVery curious about this world and blogging whenever learning something new
cardImage

The State of Consumer Digital ID 2024

cardImage

Top CIAM Platform 2024

cardImage

Learn How to Master Digital Trust

Customer Identity, Simplified.

No Complexity. No Limits.
Thousands of businesses trust LoginRadius for reliable customer identity. Easy to integrate, effortless to scale.

See how simple identity management can be. Start today!