0

In javascript/es6 module programming for browser env(with webpack), I want to optimize my process of resources loading

say, in a module, we export a class

// in a js module
export default class MyClass {
    constructor(){
        new Promise(resolve => {
            // this async IO always return unchanged remote resources
            new AsyncIOLoader.load(remoteResources, resolve)
        }).then(rawData =>
                // a slow non-IO computation is needed 
                this.data = SlowTransform(rawData) 
        )

    }
    show() {
        return this.data
    }
}

if client code intends to use for loop to create many instances of my class. that SlowTranform would be repeated many times, with SAME input and output.

And now I want to optimize it by lifting it into module scope(global scope).

for normal variable(that doesn't need async IO), it's easy:

// in a js module

//SlowTransform is still slow, but we only execute it once
const data = SlowTransform(rawData)

export default class MyClass {
    constructor(){
        this.data = data
    }
    show() {
        return this.data
    }
}

But How do we achieve this in facing of rawData that should be retrieved by Async IO ?

I think a normal Promise/then in module scope would not guarantee the availability of data when client calls new MyClass()

Bkkgbkjb
  • 9
  • 2
  • 1
    See: https://stackoverflow.com/questions/43431550/async-await-class-constructor/43433773#43433773 – slebetman Dec 12 '19 at 08:24
  • Both your concepts here are deeply flawed. You can't do either one of these this way. As this is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) where you show us your attempted solution and don't show us the overall calling code and what problem you're really trying to solve with this code, we can't really know what more proper and correct design to suggest. – jfriend00 Dec 12 '19 at 08:32
  • You pretty much never want to put asynchronous operations in a constructor for a whole variety of reasons. For a discussion of this part of the problem, see [Asynchronous operations in constructor](https://stackoverflow.com/questions/49905178/asynchronous-operations-in-constructor/49906064#49906064). – jfriend00 Dec 12 '19 at 08:34
  • If lifting the asynchronous operation out of the constructor and doing it before, then just create all your objects in the completion callback from your asynchronous operation. Asynchronous is non-blocking so there's never going to be a solution that doesn't involve a callback, a promise by itself with `.then()` or a promise with `async/await`. – jfriend00 Dec 12 '19 at 08:35

0 Answers0