kev*_*100 2 javascript asynchronous node.js
除了在bluebird中混合还是返回新的Promise()之外,有没有办法在异步函数()中处理回调函数?
例子很有趣......
问题
async function bindClient () {
client.bind(LDAP_USER, LDAP_PASS, (err) => {
if (err) return log.fatal('LDAP Master Could Not Bind', err);
});
}
Run Code Online (Sandbox Code Playgroud)
解
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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
有更优雅的解决方案吗?
NodeJS v.8.xx本身支持promisifying和async-await,所以是时候享受这些东西(:
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);
}
})();
Run Code Online (Sandbox Code Playgroud)
或者只是简单地使用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');
}
});
Run Code Online (Sandbox Code Playgroud)
PS async-await是发生器 - 产量语言构造的语法糖.
归档时间: |
|
查看次数: |
5199 次 |
最近记录: |