I need to implement an async singleton, that creates a single instance of a class that requires asynchronous operations in order to pass arguments to the constructor. I have the following code:
class AsyncComp {
constructor(x, y) {
this.x = x;
this.y = y;
}
// A factory method for creating the async instance
static async createAsyncInstance() {
const info = await someAsyncFunction();
return new AsyncComp(info.x, info.y);
}
// The singleton method
static getAsyncCompInstance() {
if (asyncCompInstance) return asyncCompInstance;
asyncCompInstance = AsyncComp.createAsyncInstance();
return asyncCompInstance;
}
}
The code seems to work fine, as long as the promise fulfils. If, however, the promise is rejected the next calls to getAsyncCompInstance()
will return the unfulfilled promise object, which means that it will not be possible to retry the creation of the object.
How can I solve this?