Node.JS Async / Await处理回调?

时间:2017-07-26 22:14:21

标签: javascript node.js asynchronous

除了在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);
    });
  });
}

有更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:6)

NodeJS v.8.x.x本身支持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');
  }
});

P.S。 async-await是发生器 - 产量语言构造的语法糖。

答案 1 :(得分:-2)

使用模块!例如pify

function bufferToString(arr){
    arr.map(function(i){return String.fromCharCode(i)}).join("")
}

尚未测试