I have a solution, but the promise chaining is not possible in this case. I used an EventEmitter (observer pattern) to attach and detach callbacks.
functionasyncCaller(asyncFun,params,thenBlock,catchBlock){constid=getRandomString(10);EventEmitterInstance.addListener(`promiseThen_${id}`,thenBlock);EventEmitterInstance.addListener(`promiseCatch_${id}`,catchBlock);constcancel=()=>{EventEmitterInstance.removeAllListeners(`promiseThen_${id}`);EventEmitterInstance.removeAllListeners(`promiseCatch_${id}`);};asyncFun(...params).then((resp)=>{EventEmitterInstance.emit(`promiseThen_${id}`,resp);}).catch((error)=>{EventEmitterInstance.emit(`promiseCatch_${id}`,error);}).finally(()=>{// need to clear the listeners at the endcancel();});returncancel;}// in the component hookReact.useEffect(()=>{constthenBlock=()=>{setText("done!");};constcatchBlock=(error)=>{console.log(error);};constcancelCall=asyncCaller(simulateSlowNetworkRequest,[],thenBlock,catchBlock);return()=>{cancelCall();};},[setText]);
here is the working code link. I reused your example
I have a solution, but the promise chaining is not possible in this case. I used an EventEmitter (observer pattern) to attach and detach callbacks.
here is the working code link. I reused your example
an improved version of the above code : link
in the useEffect hook you can do
Wow, you're brilliant!