Node.JS Async / Await Dealing With Callbacks?
This question already has an answer here:
NodeJS v.8.xx 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');
}
});
PS async-await is syntactic sugar for generator-yield language construction.
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
链接地址: http://www.djcxy.com/p/55526.html上一篇: 包装在承诺的JavaScript通用功能
下一篇: Node.JS异步/等待处理回调?