exporting after promise finishes

前端 未结 1 843
抹茶落季
抹茶落季 2020-12-19 19:25

I would like to export a class which initial state depends on a value returned from a Promise in another module i cannot modify.

Here\'s the code:

相关标签:
1条回答
  • 2020-12-19 20:16

    module exports are done synchronously. So, they cannot depend upon the results of an asynchronous operation.

    And, await only works inside a function. It doesn't actually block the containing function (the containing function returns a promise) so that won't help you make an async operation into a synchronous one either.

    The usual ways to deal with a module that uses some async code in its setup is to either export a promise and have the calling code use .then() on the promise or to initialize the module with a constructor function that returns a promise.

    The code is only pseudo code so it's hard to tell exactly what your real problem is to show you specific code for your situation.

    As an example. If you want to export a class definition, but don't want the class definition used until some async code has completed, you can do something like this:

    // do async initialization and keep promise
    let e;
    const p = APromiseFromAnotherModule().then(val => e = val);
    
    class E {
        constructor() {
            if (e) {
                //...
            } else {
                //...
            }
        }
    };
    
    // export constructor function
    export default function() {
       return p.then(e => {
           // after async initialization is done, resolve with class E
           return E;
       });
    }
    

    The caller could then use it like this:

    import init from 'myModule';
    init().then(E => {
       // put code here that uses E
    }).catch(err => {
       console.log(err);
       // handle error here
    });
    

    This solves several issues:

    1. Asynchronous initialization is started immediately upon module loading.
    2. class E is not made available to the caller until the async initialization is done so it can't be used until its ready
    3. The same class E is used for all users of the module
    4. The async initialization is cached so it's only done once
    0 讨论(0)
提交回复
热议问题