除了在bluebird中混合或返回新的Promise()之外,还有其他方法可以处理异步函数()内部的回调函数吗?
例子很有趣。。。
问题
async function bindClient () {
client.bind(LDAP_USER, LDAP_PASS, (err) => {
if (err) return log.fatal('LDAP Master Could Not Bind', err);
});
}
解决方案
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);
});
});
}
有没有更优雅的解决方案?
NodeJS V.8.x.x本机支持允诺和异步等待,因此现在是享受这些东西的时候了(:
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);
}
})();
或者只是简单地使用co
包并等待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');
}
});
附注。async-await是生成器-产出语言构造的语法糖。
使用模块!例如pify
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);
}
我还没有测试过