Sunday 29 December 2019

javascript - 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 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?


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...