Similar to other questions not not quite the same: I have a variable assignment which involves calling a function that takes a significant amount of time to run, and I want to trigger a function after that assignment finishes. (The function I want to trigger is a React setState function, if relevant).
The line of code currently looks something like this:
const data = handler.get(endpoint).then(res => setMyState("finished getting endpoint"))
Unfortunately, this seems to be assigning the result of the ".then()" segment to "data" instead of the "handler.get" segment.
Is there a way I can trigger a ‘.then()’ off of a variable assignment while capturing the value of the left half of the function chain?
2
Answers
You can use a useEffect hook with the variable you assign as a dependency
It sounds like you want Promise.prototype.finally(). This will run after the promise resolves or rejects but it will not effect the resolved value.
A simpler option is to use
async
/await
syntax instead