Home » Programming » Javascript » Javascript Promises

Promises in JavaScript: What they Are, How to Use Them

Promises are a feature of JavaScript which allow code to continue executing in the background, and perform an action with the result when it has completed. This article will show you how to use Promises.

What is a ‘Promise’ in JavaScript?

Promise is an object in JavaScript which acts as a placeholder for the eventual result of an operation.

A Promise is either:

  • Pending while the operation completes
  • Fulfilled when the operation is successful
  • Rejected if the operation fails

Promises allow for asynchronous code execution in JavaScript.

Synchronous vs Asynchronous

Asynchronous execution means that more than one thing can happen at the same time. Synchronous code is sequential – each line of code is executed one after the other. Code will not execute until the code before it has successfully executed.

Asynchronous programming means that code can be executing alongside other code, returning a result when it has completed – not based on the execution of previous lines of code. For example, you may set an asynchronous function to retrieve some data from a remote server, and continue performing other tasks while you wait for that data to download.

The Old Asynchronous Way – Function Callbacks

JavaScript is a synchronous programming language.

Historically, asynchronous tasks were performed in JavaScript using callbacks. Callback functions are functions which are called from other functions once they have completed executing. Callbacks can be synchronous or asynchronous, and were commonly used to implement asynchronous functionality.

By passing one function to another, callbacks could be chained – each function calling the next as it completes, while the main script continues to execute.

Promises for Asynchronous code

The above approach can get messy, quickly. Promises are a relatively new feature to JavaScript which adds native support for asynchronous code. Promises let you wait for the result of a function without pausing execution of your script.

Promise JavaScript Syntax

Promise is a JavaScript object. When creating a Promise you provide the code it must execute, and the actions that should be taken if the promise succeeds or fails.

Creating Promises

Promises are initialized like any other variable:

var myPromise = new Promise();

Above, a Promise is created. But it doesn’t do anything. A function must be added containing the code the Promise will execute and wait for:

var myPromise = new Promise((resolve, reject) => {

    // If your code is successful, call resolve to complete the Promise successfully
    resolve(result);

    // If your code is not successful, call reject
    reject(error);

});

Here, a Promise is created containing a function. Two parameters are passed from the Promise to the function – resolve and reject. The resolve parameter is a function that should be called with the successful result of your code, whereas the reject function should be called if there is a problem.

Note that arrow function syntax is used in the above example.

The variable passed to resolve or reject will be supplied as the result of the Promise.

Using the Result of a Promise

The result of a promise can be accessed once the Promise has succeeded (resolved) or failed (rejected). This is done using .then() and catch():

var myPromise = new Promise((resolve, reject) => {

    //  Your code here, calling either resolve() or reject()

});

myPromise.then(result => {
    // The Promise has completed successfully - the result can be accessed using the argument returned by .then()
});

myPromise.catch(error => {
    // The Promise has failed - the error or object passed to reject() can be accessed using the argument returned by .catch()
});

myPromise.finally(() => {
    // The Promise either succeeded or failed - actions can be taken here regardless of the outcome
});

Promises Examples

The simplest demonstration of a promise is to set a timeout – a delay which will delay the resolving of the Promise. You will be able to see the Promise execute, time pass, and the result return – while the rest of your code continues to execute:

console.log('Hello');

var myPromise = new Promise((resolve, reject) => {

    setTimeout( function() {
        resolve("This is the delayed result of a promise - it's asynchronous!");
    }, 1000)

});

console.log('This message will appear before the one inside the Promise');

myPromise.then(result => {
    console.log(result);
});

If you execute the above code, you will see that the messages do not appear in the sequential order they appear in the code – the promise is delayed by 1000 milliseconds – and the code after it continues executing. When the promise is resolved, the result is printed.

Real-World Example

Probably the best example, and one that you are likely to use, is the JavaScript fetch API.

The fetch API is used to access remote data via HTTP. As these network transfers take time, fetch is asynchronous, and returns a promise when called:

fetch('http://example.com/movies.json')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error));

Above, JSON data is loaded from an example URL via HTTP using fetch. A promise is returned, which is handled by two calls to then() – the first loads the JSON result of the HTTP call, and the second prints it using console.log(). If an error occurs, it is caught with catch() and printed also.

This demonstrates the brevity of using promises – using arrow function syntax and Promises, what would have otherwise been a messy series of callbacks to implement an asynchronous solution can be achieved in a few lines of code.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment