Node.JS异步/等待处理回调?

这个问题在这里已经有了答案:

  • 如何将现有的回调API转换为承诺? 17个答案

  • 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

    上一篇: Node.JS Async / Await Dealing With Callbacks?

    下一篇: How to convert a callback code to promise in ES6