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))});}
This discussion was converted from issue #200 on June 21, 2022 05:15.
Heading
Bold
Italic
Quote
Code
Link
Numbered list
Unordered list
Task list
Attach files
Mention
Reference
Menu
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
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:
Beta Was this translation helpful? Give feedback.
All reactions