Over a million developers have joined DZone.

JavaScript: How to Define and Process a Promise Object

In this post, I'll provide direction and code samples on how to create and use a Promise Object in JavaScript. Read on to see how it's done.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

This article provides tips and code samples on how to define and process a Promise object. Please feel free to comment/suggest if I failed to mention one or more important points. 

How to Define a Promise Object

The following example demonstrates an Auth module within an API login that returns a Promise that will either be resolved/fulfilled or rejected.  The returned object, will represent a domain object such as User or Error object with a status and error message, as demonstrated below:

// Promise needs to be imported when executing a module using Node
var Promise = require("promise");

function Auth() {

Auth.prototype.login = function(user) {
    return new Promise(function(resolve, reject) {
        if(user.username != "" && user.password != "") {
            resolve({username: user.username, age: 21, location: "Hyderabad", firstname: "Raju", lastname: "Mastana"});
        } else {
            if(user.username == ""){
                reject({status:1, message: "Username is invalid"});
            } else {
                reject({status:2, message: "Password is invalid"});

module.exports = Auth;

How to Process a Promise Object

The following tasks are defined in the code sample provided, which calls login API on an Auth object:

  • Create an Auth object
  • Invoke login API on Auth object
  • Invoke "then" method on Promise object returned from the invocation of login API.
// Import the Auth module
var Auth = require('./Auth');

// Create an Auth object
var auth = new Auth();
// Calls login API on Auth object
// Returns a promise object
var loginPromise = auth.login({username:'', password:'pass123'});
// Once the state of Promise is fulfilled/resolved or rejected,
// following is executed
    console.log("User name: " + response.name);
}, function(error) {

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

javascript,angular js,promise,promises,promises in javascript

Published at DZone with permission of Ajitesh Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}