Node.JS异步/等待处理回调? [英] Node.JS Async / Await Dealing With Callbacks?

查看:96
本文介绍了Node.JS异步/等待处理回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了混入bluebird或返回新的Promise()之外,是否有一种方法可以处理异步函数()中的回调函数?

Is there a way to deal with callback functions inside an async function() other than mixing in bluebird or return new 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);
    });
  });
}

有没有更优雅的解决方案?

Is there a more elegant solution?

推荐答案

NodeJS v.8.x.x原生支持promisifying和async-await,因此现在该享受这些东西了(:

NodeJS v.8.x.x 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);
  }
})();

或仅使用 co <​​/code>包并等待对async-await的本机支持:

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');
  }
});

P.S.async-await是用于生成器生成语言的语法糖.

P.S. async-await is syntactic sugar for generator-yield language construction.

这篇关于Node.JS异步/等待处理回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆