Search code examples
javascriptajaxpromiseecmascript-5

Hold on callback function execution until promise is completed


I have some third party library whose events I'm listening. I get a chance to modify data which that library is going to append in the UI. It is all fine until that data modification is synchronous. As soon as I involve Ajax callbacks/promises, this fails to work. Let me put an example to show case the problem.

Below is how I'm listening to a event:-

d.on('gotResults', function (data) {

  // If alter data directly it works fine.
  data.title = 'newTitle';
  // Above code alters the text correctly.

  //I want some properties to be grabbed from elsewhere so I make an Ajax call.
  $.ajax('http://someurl...', {data.id}, function (res) {
    data.someProperty = res.thatProperty;
  });
  // Above code doesn't wait for ajax call to complete, it just go away and 
  renders page without data change.


  // Yes I tried promises but doesn't help
  return fetch('http://someurl...').then(function (data) {
    data.someProperty = res.thatProperty;
    return true;
  });
  // Above code also triggers the url and gets away. Doesn't wait for then to complete.

});

I cannot change/alter the third party library. All I have is to listen to event and alter that data.

Any better solutions. Nope. I can't use async/wait, generators, because I want to have it supported for ES5 browsers.


Solution

  • You cannot make a synchronous function wait for an asynchronous response, it's simply not possible by definition. Your options pretty much are:

    1. BAD IDEA: Make a synchronous AJAX request. Again: BAD IDEA. Not only will this block the entire browser, it is also a deprecated practice and should not be used in new code, or indeed ever.

    2. Fetch the asynchronous data first and store it locally, so it's available synchronously when needed. That obviously only works if you have an idea what data you'll be needing ahead of time.

    3. Alter the 3rd party library to add support for asynchronous callbacks, or request that of the vendor.

    4. Find some hackaround where you'll probably let the library work with incomplete data first and then update it when the asynchronous data is available. That obviously depends a lot on the specifics of that library and the task being done.