Delay the execution of the callback function until the promise has been fulfilled

I am facing an issue with a third-party library that I am listening to for events. When I try to modify the data it appends to the UI synchronously, everything works perfectly. However, once I introduce Ajax callbacks or promises into the mix, the functionality breaks down. Let me illustrate the problem with an example.

Here is how I am listening to an event:

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

  // Modifying data directly works fine.
  data.title = 'newTitle';
  // The above code successfully changes the text.

  //I need to retrieve some properties from elsewhere so I make an Ajax call.
  $.ajax('http://someurl...', {data.id}, function (res) {
    data.someProperty = res.thatProperty;
  });
  // The above code does not wait for the Ajax call to complete and renders the page without the data change.


  // I have also tried using promises but to no avail
  return fetch('http://someurl...').then(function (data) {
    data.someProperty = res.thatProperty;
    return true;
  });
  // The above code also triggers the URL request and moves on without waiting for the promise to be fulfilled.

});

I am unable to alter the third party library itself. My only option is to listen to the event and modify the data accordingly.

Unfortunately, there are no better solutions available as I cannot use async/await or generators since I need to ensure compatibility with ES5 browsers.

Answer №1

It is impossible to make a synchronous function wait for an asynchronous response by definition. There are several alternatives you can consider:

  1. NOT RECOMMENDED: Attempting a synchronous AJAX request. This method should be avoided as it blocks the browser and is considered deprecated.

  2. Retrieve the asynchronous data in advance and store it locally for synchronous access when needed, if possible based on your knowledge of the required data.

  3. Modify the 3rd party library to incorporate support for asynchronous callbacks, or request this feature from the vendor.

  4. Implement a workaround where the library initially operates with incomplete data and then updates once the asynchronous data becomes available. The feasibility of this approach depends on the specifics of the library and the task at hand.

Answer №2

Is it necessary for the gotResults callback function to return anything other than true? If not, you could implement regular asynchronous code without relying on this specific library. Allow me to elaborate by adjusting your pseudocode:

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

  // Modifying data directly works properly.
  data.title = 'newTitle'; 

  // I need certain properties from another source, so I am making an Ajax call.
  $.ajax('http://someurl...', {data.id}, function (res) {
    data.someProperty = res.thatProperty;

    // The above code does not wait for the ajax call to finish before moving on
    // EDIT: It should now render correctly

    // I attempted using promises, but it did not resolve the issue
    return fetch('http://someurl...');
    // The above code also triggers the url and moves on without waiting for completion
    
  }).then(function (data) {
    data.someProperty = res.thatProperty;
    
    // Should we consider rendering again at this point?
  }).catch(function(err) { 
    handleError(err); // Ensure errors are handled instead of being ignored silently
  });
  return true; // This line executes before any of the asynchronous code above, but is it important?
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

Decoding JSON data from an AJAX call

I'm currently facing an issue with parsing JSON data in an AJAX response within JSP. The response consists of a list of objects, and I am unable to extract individual variables from it. Below is the code snippet for reference. JsonTest.jsp <html& ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

Obtain the final result once all promises have been successfully resolved in a loop

Here is an array of IDs: let idsArray = [1, 2, 3, 4, 5]; How can I ensure that a promise is returned only after all calls made within the loop are completed? let deferredPromise = $q.defer(), finalResult = []; fo ...

Smooth transitions: How AJAX calls to PHP chats revolutionize page navigation

When I click the "send button," the page automatically scrolls to the top, which is not the expected behavior. Any suggestions on how to fix this? I've already tried using animations and return false, but nothing seems to be working. Check out the JSF ...

The case-insensitive flag 'i' is ineffective when using JQuery to filter data

I am trying to filter a list based on a search string while maintaining case insensitivity. However, I encountered an issue where the i flag for case-insensitivity works in a normal jQuery selector, but not in the filter selector. Could this be a bug or is ...

Enhancing Nested Objects using Mongoose

When attempting to update nested objects using Mongoose, the request I receive appears like this: { 'example[apple]': 'false', 'example[pear]': 'false', 'example[banana]': 'false', 'example[ ...

JS: Modifying this function to manage a click on a hyperlink

After following the guide provided here I have successfully implemented a drop down list that sends the value to an external PHP script, retrieves HTML output, and displays it in a "div" on the same page. It works flawlessly. My next objective is to send ...

Placing a blank span after the highlighted text

Currently, I am developing a dictionary feature that allows users to select text and view the definition of the word or phrase by hovering over it for a second. It's a simple concept, but my implementation is quite basic so far. I'm using the mou ...

Error: Attempting to access the 'getCroppedCanvas' property of an undefined value in VueJs

I've been exploring the vue-cropperjs library, but every time I execute the code, I encounter error messages: Uncaught TypeError: Cannot read property 'getCroppedCanvas' of undefined Uncaught TypeError: Cannot read property 'replace&ap ...

What is preventing my content from showing up when clicked like this?

I have created a javascript script to reveal hidden content, but for some reason it is not working when I click on it. Can anyone provide assistance? Below is the script I am using: <script src="style/jquery/jquery.js"></script> <script> ...

What is the simplest way to test an npm module while coding?

Currently, I am in the process of making modifications to @editorjs/nested-list. To streamline my testing process without extensive installations, I have created a simple web page: <html> <head> <script src="https://cdn.jsdelivr.net/npm ...

Introducing a fresh addition to the array

I am looking for a way to create a new array without modifying the original one. Currently, there is a function that adds a new object to an existing array, but I need a different method to achieve this. Can someone suggest a solution? const arr = [ ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

When the page is fully loaded, I am trying to utilize jQuery with functions like $(window).ready(), but unfortunately, it does not seem to be functioning as expected

Utilizing jquery to dynamically adjust the content on my html page based on the page width. Upon the page being fully loaded (using the $(document).ready(function({\\there is some code here!}));), I aim to execute certain functions. My objectiv ...

The art of tidying up Angular UI controllers

I am a beginner with Angular and have integrated angular-ui to use bootstrap modals for adding data. It seems inefficient to have to include all these functions in EVERY controller where I want to use a modal. Is there a way to make this more reusable? ...

Tips on changing the URL of the current tab after clicking on a link

const selenium = require('selenium-webdriver'); require('chromedriver'); const By = selenium.By; const driver = new selenium.Builder().forBrowser('chrome').build(); const url = 'https://example.com'; driver.get(url) ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Using PHP and JavaScript to determine device screen width and eliminate the $_GET parameters from the URL

I have implemented the following JavaScript code to detect screen width and utilize it as a constant throughout my template files using conditional statements to control the visibility of different sections on my site. Just to clarify, I am working within ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...