0

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
Pål Thingbø
  • 1,211
  • 1
  • 17
  • 17

1 Answers1

2

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.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308