2

I'm updating a "legacy" React application which fetches data asynchronously through $.ajax.

The data fetched is a mandatory property for a child component, so it should be available right away. I thought I'd fetch the data in the constructor. It was solved until now with a call to ReactDOM.render in the done callback, but this has some drawbacks (i.e. it won't re-render properly on viewport changes).

The problem boils down to this:

$.when(API.fetchSomething(), API.fetchAnother()).done(([firstResult], [secondResult]) => {
  console.log("run this first"); 
  this.first = firstResult;
  this.second = secondResult;
}).someMagicWaitMethod();

console.log("then run this");
console.log(this.first, this.second); // must be available right now!

How can I wait in a proper way for the async calls to finish until continuing with the execution?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
jogo
  • 134
  • 1
  • 9
  • 1
    https://stackoverflow.com/questions/48978639/await-for-jquery-when-ajax-requests – epascarello Jan 28 '21 at 17:15
  • 1
    There is nothing magic you can do to force code to wait. Is there a reason you can not do the stuff inside the when callback? – epascarello Jan 28 '21 at 17:16
  • 1
    '*How can I wait in a proper way for the async calls to finish until continuing with the execution?*' in the callback, as you already are. I'm not sure what the issue is here. This seems to be an X/Y situation. – Rory McCrossan Jan 28 '21 at 17:32
  • 1
    `.when()` is a jQuery method to pass in "defered" objects and a callback to execute at a later time **WHEN** it resolves. The method name is quite self-explanatory. "I will execute a function WHEN the promise(s) resolves". -- So please google about `promise`, `asynchounous functions`, `callbacks`, etc. I am closing your question as a duplicate. – Louys Patrice Bessette Jan 28 '21 at 19:36
  • Don't use `$.when`, use `Promise.resolve($.ajax(…))`. Then use the standard promise API. – Bergi Jan 28 '21 at 19:38

0 Answers0