0

Under Inheritance, when a child object extends the parent, the parent needs to be constructed first before the child can be created.

However, one of the properties of parent constructor is async (webSQL database transaction). I want to share the database transaction object to all of it's children.

But then the problem is children can't use the transaction object right away because it gets created some time later asynchronously after the parent creation.

Parent:

    if(this.database = common.model.connections.Sync.getConnection()) {
        this.database.transaction(function(transaction){
            self.transaction = transaction;
        });
    }

Please advise or ask me for more details. Will appreciate any design patterns.

user2727195
  • 7,122
  • 17
  • 70
  • 118
  • Not sure if I entirely understand your question, but I think you're looking for Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – ndugger Sep 03 '14 at 16:37
  • thanks @NickDugger for the attempt, it's new for me, but won't be able to use since it won't work across browsers, but it seems similar to what I'm thinking. i.e. Pass a callback method (let's say startup) of the child object to the parent object in the constructor, and then parent will call the callback once the async property (database transaction) gets created. – user2727195 Sep 03 '14 at 16:43
  • There are polyfills for Promises. I highly suggest you give it a try – ndugger Sep 03 '14 at 17:42
  • What I understood from my brief research that it's to reduce nesting of callbacks and make the code more organized, but I feel my question is more architecture related, even if you forget for a minute that we are in javascript, let's say a parent's property get's created asynchronously, so basically child is not fully complete right away, it also means the parent has to know the child. – user2727195 Sep 03 '14 at 20:36
  • Performing database operations in a constructor looks odd to me. – plalx Oct 24 '14 at 19:12
  • it's there just to bring the transaction in the scope, then other functions act via this.transaction for sql queries – user2727195 Oct 24 '14 at 19:16
  • here is an async constructor: https://stackoverflow.com/a/45872568/466363 – Shimon Doodkin Aug 26 '17 at 18:37

1 Answers1

0

Async constructors are not supported explicitly. However, there is a straightforward solution: if you can't put the object in the promise, put the promise in the object. In practice this turns out to be a better solution anyway, since you can then check resolution status anywhere you have a reference to the object, not just at the point of construction.

I refer you to my answer to a related question.

async constructor functions in TypeScript?

Peter Wone
  • 17,965
  • 12
  • 82
  • 134