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:
- Asynchronous initialization is started immediately upon module loading.
- class E is not made available to the caller until the async initialization is done so it can't be used until its ready
- The same
class E
is used for all users of the module
- The async initialization is cached so it's only done once
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…