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.
Join the DZone community and get the full member experience.
Join For FreeThis 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);
});
Published at DZone with permission of Ajitesh Kumar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments