Working with promises in node JS

Posted By : Ekesh Bahuguna | 19-Dec-2018

Promises in node js:

Promises in node.js are supposed to do work and have different handler callbacks for success and failure as well as handling timeouts. In other words, promises are emitters that could throw success and failure events. Promises can be combined into dependency chains (do Promise C only when Promise A and Promise B complete). The real problem with callbacks it that they do not allow us of using keywords like return and throw. Instead, program flow based on the effects such as function calling another one. Promises make the asynchronous code more readable and act like synchronous code without hiding that fact. Promises are all about making the asynchronous code more readable and behave like synchronous code without hiding that fact.  

 

Writing promise:

somePromise().then(function () {

});


What a promise can do:
1- return another promise
2- return a synchronous value (or undefined)
3- throw a synchronous error


1- return another promise

getUserByName('ekesh').then(function (user) {
  return getUserAccountById(user.id);
}).then(function (userAccount) {
  // got user account
});

2- return a synchronous value (or undefined)

getUserByName('ekesh').then(function (user) {
  if (inMemoryCache[user.id]) {
    return inMemoryCache[user.id];    // return a synchronous value!
  }
  return getUserAccountById(user.id); // return a promise!
}).then(function (userAccount) {
  // got user account!
});

3- throw a synchronous error

getUserByName('ekesh').then(function (user) {
  if (user.isLoggedOut()) {
    throw new Error('user logged out!'); // throw a synchronous error!
  }
  if (inMemoryCache[user.id]) {
    return inMemoryCache[user.id];       // return a synchronous value!
  }
  return getUserAccountById(user.id);    // return  a promise!
}).then(function (userAccount) {
  // got a user account!
}).catch(function (err) {
  // got an error!
});

With callbacks, every error needs to be handled manually, but with promises, we can simply handle it inside our catch() function.


Advantages of using promises :

After using promises, the code will become smaller, more elegant, and easier to reason about. Sometimes promises become difficult and error-prone. 


More ways to create promises :


1- For most values x, this promise returns a Promise that is fulfilled with x:

Promise.resolve('abc')
  .then(x => console.log(x)); 

2- Returns a Promise that is rejected with err

const myError = new Error('Problem!');
Promise.reject(myError)
.catch(err => console.log(err === myError));
 
 
 
 
 
 

 
 
 
 
 
Request for Proposal

Recaptcha is required.

Sending message..