Skip to content Skip to sidebar Skip to footer

Node.js Async / Await Dealing With Callbacks?

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 bindClie

Solution 1:

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 resulttry {
    clientInstance = awaitbindClient(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 = yieldbindClient(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.

Solution 2:

Use modules! pify for instance

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

Haven't tested it yet

Post a Comment for "Node.js Async / Await Dealing With Callbacks?"