Pål Thingbø Pål Thingbø - 1 year ago 96
Node.js Question

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) {

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

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

Answer Source

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() { /* ... */ }

  .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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download