Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS Async / Await Dealing With Callbacks? [duplicate]

Is there a way to deal with callback functions inside an async function() other than mixing in bluebird or return new Promise()?

Examples are fun...

Problem

async function bindClient () {
  client.bind(LDAP_USER, LDAP_PASS, (err) => {
    if (err) return log.fatal('LDAP Master Could Not Bind', err);
  });
}

Solution

function bindClient () {
  return new Promise((resolve, reject) => {
    client.bind(LDAP_USER, LDAP_PASS, (err, bindInstance) => {
      if (err) {
        log.fatal('LDAP Master Could Not Bind', err);
        return reject(err);
      }
      return resolve(bindInstance);
    });
  });
}

Is there a more elegant solution?

like image 671
kevingilbert100 Avatar asked Jul 26 '17 22:07

kevingilbert100


1 Answers

NodeJS v.8.x.x natively supports promisifying and async-await, so it's time to enjoy the stuff (:

const 
  promisify = require('util').promisify,
  bindClient = promisify(client.bind);

let clientInstance; // defining variable in global scope
(async () => { // wrapping routine below to tell interpreter that it must pause (wait) for result
  try {
    clientInstance = await bindClient(LDAP_USER, LDAP_PASS);
  }
  catch(error) {
    console.log('LDAP Master Could Not Bind. Error:', error);
  }
})();

or just simply use co package and wait for native support of async-await:

const co = require('co');
co(function*() { // wrapping routine below to tell interpreter that it must pause (wait) for result
  clientInstance = yield bindClient(LDAP_USER, LDAP_PASS);

  if (!clientInstance) {
    console.log('LDAP Master Could Not Bind');
  }
});

P.S. async-await is syntactic sugar for generator-yield language construction.

like image 97
num8er Avatar answered Nov 14 '22 20:11

num8er