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

4
  • 1
    co returns a Promise, that you don't resolve. Commented Aug 28, 2016 at 7:51
  • When you see a pure dot notation sequence of properties without any callback (lke new MyObject().runSomething()), it is synchronous. You need a callback in the main code. Commented Aug 28, 2016 at 8:50
  • Don't do it! Allow new MyObject() to be wholly synchronous and relegate anything async to method(s) of MyObject(). Commented Aug 28, 2016 at 10:53
  • 1
    That's what I've done @Roamer. Thanks. Commented Aug 29, 2016 at 12:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I was suspecting this was the only path when using new.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.