I have multiple functions reading from/writing to the same file. The functions are called after certain HTTP requests. Thus, to avoid conflicts when accessing the same file simultaneously, I build some kind of promise chain:
class PromiseChain {
private current: Promise<any> = Promise.resolve();
public push<T, TResult1 = T, TResult2 = never>(
onfulfilled?:
| ((value: T) => TResult1 | PromiseLike<TResult1>)
| undefined
| null,
onrejected?:
| ((reason: any) => TResult2 | PromiseLike<TResult2>)
| undefined
| null
): Promise<TResult1 | TResult2> {
return (this.current = this.current.then(onfulfilled).catch(onrejected));
}
}
which can be used like so:
const chain = new PromiseChain();
const defer = (message: string, timeout: number) => () =>
new Promise((resolve) => setTimeout(() => resolve(message), timeout)).then(
console.log
);
chain.push(defer('1st', 1000), (error) => console.log(error.message));
chain.push(defer('2nd', 500));
Thus, the promises are being executed in the same order they have been pushed to the chain (1st
then 2nd
). Errors along the chain can be caught, so the chain will not break.
Is there any built-in or an easier way to achieve this? I was thinking along the lines of rxjs Subjects or the like.