Clean interface that supports Callbacks, Promises and async/await

时间:2018-06-04 17:11:19

标签: node.js ecmascript-6

I'm in the process of building a small Library that relies heavily on asynchronicity and I'm trying to support NodeJs callback style, Promises and async/await with minimal duplication of functional code.

So, as example take the following ( it doesn't matters what it does)

class Someclass{
  constructor(){}

  asyncMethod(someData, cb){
    var commonVar = ''
    if (cb) { // ******* Callback Requested
      doSomething()
      var result=usingCallbacks()
      if (!result) cb('Error')
      cb(null, result)
    } else{ // ******** we should use a promise
      return new Promise((resolve,reject) => {
        doSomething()
        var result=usingPromises()
        if (!result) reject(err)
        resolve(result)
      })
    }
  }
}

So i'm stuck on how to build the async/awit part here. Any ideas?

1 个答案:

答案 0 :(得分:1)

Nothing else is required since await can await anything that returns a Promise (or something promise-like).

In other words, this should "just work":

async useLibFn() {
  await someclass.asyncMethod('foo');
}

Under the covers, async/await are just syntactic sugar for promises.

  • async causes a function to always return a promise. Basically equivalent to:

    function someFn() {
      return new Promise(function(resolve, reject) {
        try {
          // actual fn body
        } catch (ex) {
          reject(ex);
        }
      });
    }
    
  • await takes some expression and resolves it asynchronously. If the value is promisey, it waits for the promise to resolve (calls then()). Otherwise, it resolves with the value on the next tick. Basically equivalent to:

    Promise.resolve(rval).then(...)