I need to pass a function creating a Promise and have an availability to start it again. The Promise is one time state machine, so there is no restart functionality. This answer suggests to wrap a Promise in a function. But my attempts either do not work or do not compile.
This is an interface:
export interface LoaderContext {
action: Promise<any>;
}
export class LoaderMachine {
private readonly initialContext: LoaderContext;
constructor(action: Promise<any>) {
this.initialContext = { action, retries: 0 };
}
Here I use the service, the method can be called multiple times:
async fetchData(context: LoaderContext) {
try {
await context.action;
} catch (err) {
console.error(`Failed with ${err}`);
}
}
A sample Promise I use for testing
function executeRequest() {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
if (new Date().getSeconds() % 5 > 1) {
reject('Bad luck');
} else {
resolve();
}
}, 3000)
});
}
And how I call it:
this.loaderService = new LoaderMachine(executeRequest()).service;
How to adapt a Promise in a function so I can call it multiple time? Or did I misunderstood that answer? I need to pass such functions:
this.setupConfig()
this.getUserCredentials.bind(this)