javascriptnode.jspromiseco

new object with async routines


I want to instantiate an object where the constructor performs async calls before returning. The purpose is to do async currying. I am using co. The below example fails. What am I doing wrong?

var co = require('co')

function asyncFunction() { 
  return new Promise(function (resolve) {
    resolve()    
  })
}

function MyObject () {
  co(function * () {
    yield asyncFunction()
  }).then(()=> {
    this.runSomething = function() {
      return 'something'
    }
  })
}

new MyObject().runSomething()
// TypeError: (intermediate value).runSomething is not a function


Solution

  • A new operator will always return an object immediately, and synchronously. You can't delay that operation.

    You could instead create a function that will return a Promise for your object.

    function makeObjectAsync() {
      const asyncResult = asyncOperation();
      return asyncResult.then(result => ({
        runSomething() { /* ... */ }
      }));
    }
    
    myObjectAsync()
      .then(obj => {
        // obj is ready to use.
        return obj.runSomething();
      });
    

    You can combine that with co fairly easily to get read of some of the .then()s.