Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript: How to Define and Process a Promise Object

DZone's Guide to

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 ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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
//
loginPromise.then(function(response){
    console.log("User name: " + response.name);
}, function(error) {
    console.log(error.message);
});

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
javascript ,angular js ,promise ,promises ,promises in javascript

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}