noober noober - 6 months ago 27
Javascript Question

Client JS: Return concatenation of async requests

{6688C2CF-1A11-4AEE-B8CC-2969353B21EA}

Answer

Here's a discussion of various options:

  1. Use synchronous Ajax and return the result. Synchronous ajax is a horrible idea and the challenge said to use async requests so presumably this is a no-go, but I include it here because it does let you directly return the result.

  2. If you use async ajax in the same window, then you simply cannot return the result directly. You can call a callback when the result is done or you can return a promise which will then call a .then() handler callback when the result is available. You cannot spin and wait for the async ajax to finish because the Ajax complication can't get back to you until you return and let the event queue get to the next events.

  3. If you put Ajax into a webWorker (either synchronous or asynchronous), you can code the webWorker however you want, but the only way it can communicate back to the main thread is via a message and that message can't be received by the main thread until you return back from your original function to get to the next messages in the event queue. Again, you can't spin and wait for the message from the webWorker because it won't get back to you until AFTER the current thread of execution finishes. So, you have to return from your function BEFORE you can get the result from the webWorker.

  4. You can put the Ajax into an iFrame or another window and then communicate back to the current window from the other window when it is done. This has all the same issues as the previous solutions in that you won't be able to receive communication back from the iFrame or other window until after the current function has finished and returned so that events can get processed off the event queue. So, you have to return from your function BEFORE you can get the result from another window.

  5. You can put the Ajax into an iFrame or another window and then poll some variable in that window from your main window. There is a possibility that this might work in some browsers, but I was unable to build a successful test to prove it could work.