Tips on setting a variable using an asynchronous xmlhttprequest reply

In order to achieve my goal, I initially utilized synched requests which made the process easier. However, now that this method is deprecated, I am in the process of updating my script to utilize asynchronous calls instead. This adjustment ensures that even if the previous method becomes obsolete, my script will continue to function smoothly.

The current code snippet I am working with is outlined below:


function GET(a) {
  var request = new XMLHttpRequest(),
    data;
  request.open("GET", a, false);
  request.onreadystatechange = function () {
    if(4 == request.readyState) data = request.responseText;
  };
  request.send();
  return data;
}

function getObject(a) {
  var constructor = {};
  constructor.property1 = 'something1';
  constructor.property2 = 'something2';
  constructor.property3 = 'something3';
  constructor.property4 = true;
  if(a && a.attribute === null) constructor.property5 = GET('/url-location');
return constructor;
}

var object = getObject(a);
if(object.property5) doSomethingWith(object);

Currently, the request is executed at runtime to assign a value to the constructor object. The synchronous nature of this setup allows the function to wait for a response before progressing, ensuring a value can be assigned prior to returning the object.

However, when running asynchronously, the function moves forward without waiting for the response, leading to complications.

My dilemma lies in whether it is feasible to replicate this behavior using asynchronous requests. If not, how can I attain a similar structure without extensive modifications? Specifically, the creation of the constructor object must remain as presented - setting multiple properties sequentially upon calling getObject and returning when completed.

I am unable to incorporate libraries such as jQuery or Node. Additionally, I aim to avoid timed/looped functions.

An important detail that should not go unnoticed: the GET function is employed by another function with a different configuration but serves a comparable purpose. Therefore, altering the GET function solely for the provided example is not a viable solution.

Answer №1

Inject a callback function into your GET, and then invoke it:

function GET(a, callback) {                                     
  var request = new XMLHttpRequest();                           
  request.open("GET", a, true);
  request.onreadystatechange = function () {
    if(4 == request.readyState) callback(request.responseText); 
  };
  request.send();
}

Example (also utilizing a callback):

function retrieveObject(a, callback) { 
  var obj = {};
  obj.property1 = 'something1';
  obj.property2 = 'something2';
  obj.property3 = 'something3';
  obj.property4 = true;
  if(a && a.attribute === null) GET('/url-location', function(data) {
    obj.property5 = data;
    callback(obj);
  });
}

Implementation:

retrieveObject(a, doSomethingWith);

Alternatively, if you require an object variable:

var object;
retrieveObject(a, function(data) {
    object = data;
    doSomethingWith(object);
});

Please note that the object will remain undefined until the callback is executed (e.g., when the XHR call finishes).

Another approach involves using promises, which still rely on callbacks but offer a different (and arguably more robust/convenient) method of chaining them together.

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

Steps to briefly pause browser rendering and then resume for the entirety of the page

Although it may seem strange at first glance, I urge you not to dismiss this idea as nonsense without giving it a chance. Suspending and resuming rendering is a common practice in many UI frameworks such as Java GUIs and .NET, with the main goal being to ...

Guide for setting up a React infinite scroll feature in a messaging app similar to Facebook Messenger

I have been exploring various questions regarding React infinite scroll, but I am looking to delve deeper in order to discover the most effective solution available for implementing such a component. Currently, I am working on a chat application and have ...

The data from the Subscribe API call is gradually loading within the ngOnInit() function

When using Angular 8, I am experiencing slow data retrieval when making API calls in the ngOnInit() function. The issue arises when trying to pass this data as @Input from one component module to another - it initially comes through as undefined for a minu ...

Issue with triggering onclick event in both parent and child components

I am working with 2 components in Vue.js: An Accordion header that opens its content when clicked on. A Cog icon that opens a mini-modal menu. The issue arises when I click on the cog icon - I do not want the Accordion to open its content. Before click ...

In JavaScript, an HTTP request file includes a JavaScript variable

I am currently working on a Node.js project that involves making an HTTP request to fetch a JavaScript file. For example, let's say we have a file named a.js: var a = 'i am a.js'; var b = 'please convert me to js'; Here is the a ...

Transform the v-model value from numerical to textual representation

Currently, I am using the <q-select> component and populating it with options fetched from an API. The issue arises when setting the value as the ID of the object, which is a number while the component expects a string, resulting in an error. <s- ...

Error: The regeneratorRuntime is not defined. This error occurs in the Chrome console and is not related to the gulp/babel build process

Currently facing a perplexing issue that requires some assistance. I've been working on a WordPress theme using gulp & babel in a development environment, with separate hosting for dev and production. Thus far, building and testing the theme in t ...

Issues with displaying Angular Material's ng-messages in a dialog box

While working on a login form within a dialog, I noticed that the ng-messages for the respective input are not appearing. The validation is functioning properly as the input turns red when there's an error, and the button remains disabled until the va ...

Click on every link to reveal a hidden div

When I click on and select the first link in the mainPart, I want to automatically select the first subLink div in the secondPart while hiding the other subLink classes. This sequence should be maintained: when the second link is selected, the second sub ...

Ways to align the label at the center of an MUI Textfield

My goal is to center the label and helper text in the middle of the Textfield. I managed to achieve this by adding padding to MuiInputLabel-root, but it's not responsive on different screen sizes (the Textfield changes size and the label loses its cen ...

Determine the number of rows in the Tabulator's table

Can anyone tell me how to retrieve the number of rows in a table created using Tabulator on a website? Is there a method like table.size or table.length that I can use for this purpose? The table has been initialized with the following code: table = new T ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

Export a function within a function to be used in another file in Javascript

I'm encountering an issue regarding exporting a function within a function to another function in a separate file, while working with the React framework. The code snippet provided below is not functioning as expected, despite my attempts to troubles ...

"Can you guide me on how to display a React component in a

I have a function that loops through some promises and updates the state like this: }).then((future_data) => { this.setState({future_data: future_data}); console.log(this.state.future_data, 'tsf'); }); This outputs an array o ...

JavaScript function that loads different configuration files based on the URL

My mobile website currently fetches a config.json file using the provided JavaScript code: $.ajax({ type:'GET', url: '/config.json', contentType: 'plain/text; charset=UTF-8', dataType: 'js ...

Strip away all HTML attributes within a string

I am in the process of developing an internal tool that allows a designer to input exported svg code into a text area and have the html code displayed in a syntax highlighter () When they paste their code like this <svg xmlns="http://www.w3.org/20 ...

Mongoose retrieves the entire document, rather than just a portion of it

I'm currently experiencing an issue with my mongoose query callback from MongoDB. Instead of returning just a specific portion of the document, the code I'm using is returning the entire document. I have verified that in the database, the 'p ...

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

How can data tables be generated using AJAX, JSON, HTML, and JS?

HTML: <table> <tr> <th>Student Name</th> <th>Student Grades</th> </tr> <tr> <td> <select name="dropdown" id= ...

Utilizing 'this' in jQuery: Image swapping with thumbnails, Twitter Bootstrap framework

Is it possible for jQuery's 'this' to simplify my code? You can view the full code here. Thank you for any help or suggestions. Here is the jQuery code: /* Ref: http://api.jquery.com/hover/ Calling $( selector ).hover( handlerIn, handler ...