Node.JS异步/等待处理回调?
这个问题在这里已经有了答案:
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);
}
})();
或者只是简单地使用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');
}
});
PS 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);
}
还没有测试过
链接地址: http://www.djcxy.com/p/55525.html