You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I know I know you can't cancel a Promise. But you can create a Promise that never resolves using the Promise constructor. So my idea is to create a util that effectively cancels a Promise when the component is destroyed. Some people say that Observable is strictly better than Promise, but I would suggest that it depends on your use case. Sometimes a Promise does all you need and with less code. This utility would make Promises good enough in even more scenarios. And then you get async/await syntax.
Usage example:
conststuff=awaitunlessDestroyed(fetch('http://example.com/stuff'));console.log("Fetched stuff. The component was not destroyed.");
Possible implementation:
/// Returns a new promise that resolves the same as the provided/// promise, unless the component is destroyed first, in which/// case the returned promise will never resolve.functionunlessDestroyed<T>(promise: Promise<T>): Promise<T>{returnnewPromise((resolve,reject)=>{letdestroyed=false;constdestroySub=destroySubject.subscribe(()=>{destroyed=true;});functionfinish<U>(callback: (u: U)=>void){return(data: U)=>{destroySub.unsubscribe();if(!destroyed){callback(data);}};}promise.then(finish(resolve),finish(reject))});}
The text was updated successfully, but these errors were encountered:
I know I know you can't cancel a Promise. But you can create a Promise that never resolves using the Promise constructor. So my idea is to create a util that effectively cancels a Promise when the component is destroyed. Some people say that
Observable
is strictly better thanPromise
, but I would suggest that it depends on your use case. Sometimes aPromise
does all you need and with less code. This utility would make Promises good enough in even more scenarios. And then you get async/await syntax.Usage example:
Possible implementation:
The text was updated successfully, but these errors were encountered: