Asynchronous operations using Promises in ES6

The Promise object in ES6 makes asynchronous programming in JavaScript easier. Asynchronous method calls are most useful in case of long-running function calls such as AJAX calls to a backend method. We dispatch a function call and take care of its result when it is done without holding up the main execution thread.

A Promise object accepts two functions: resolve and reject which can be called within the Promise depending on its outcome.

Here’s a basic example of initialising a Promise object:

let promise = new Promise((resolve, reject) => {
  resolve()
}

That’s probably as bare-bone as it gets. We resolve the promise immediately which indicates a successful outcome. We can even return a payload along with resolve and reject:

let promise = new Promise((resolve, reject) => {
  let success = {'message': 'all good'}
  resolve(success)
})
let promise = new Promise((resolve, reject) => {
  let failure = {'exception': 'what are you doing???'}
  reject(failure)
})

The Promise object has two important functions that can be chained. Both return another Promise object which is the basis for the chaining feature. These two functions are the following:

  • then: this is called if the Promise it is attached two completed without errors, i.e. if it executed the resolve callback
  • catch: this is an exception handler which is executed in case of a reject outcome of the Promise

Promise continuations will typically have at least one then and one catch functions like in the following example:

promise.then(response => console.log(response.message))
	.catch(e => console.log(e.exception))

The response variable is the payload returned via the resolve function. Response.message refers to the message property of the success variable declared in the body of the Promise constructor. Similarly the exception message is available in the catch clause via the exception object, here called “e”.

The above examples do very little and make no sense really since there’s no time consuming operation involved. We can simulate one using the standard setTimeout function as follows:

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      let success = {'message': 'all good'}
      resolve(success)
    }, 5000)
  })
 
promise.then(response => console.log(response.message))
	.catch(e => console.log(e.exception))

The success message will appear in the console log after 5 seconds.

Keep in mind that Promises will run on another thread, they don’t hold up the main thread. Here are two functions that are then called one after the other:

function executePromise() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      let success = {'message': 'all good'}
      resolve(success)
    }, 5000)
  })
  promise.then(response => console.log(response.message))
	.catch(e => console.log(e.exception))
}

function executeNormal() {
  console.log('I will most probably be executed first')
}

executePromise()
executeNormal()

Check the log messages and you’ll see that executeNormal() won’t wait for executePromise() to be executed. It won’t wait for executePromise to finish.

View all posts related to JavaScript here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: