What is the best way to save the output of an asynchronous (AJAX) function in a variable?

This isn't a repeat query.

I'm seeking assistance in locating a technical solution that hasn't been covered in the post How do I return the response from an asynchronous call?

If .then() doesn't resolve the Promise, how can I pinpoint the issue at that stage? It appears I may have overlooked something from a technical perspective, rather than conceptually.

Here is a function that fetches data from a URL:

async function getINFO(source, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", source);
    xhr.responseType = "document";
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200){
            var text = xhr.responseXML.getElementsByTagName('pre')[0].innerHTML;
            console.log(text);
            callback(text);
    }
  }
  xhr.send();
}

An externally defined callback:

function asyn_return(input){
  console.log(input);
  return input;
}

The retrieved data functions perfectly using AJAX.

I want to populate an attribute member (datastore.info) with this data.

info is a string containing a URL.

Below is where I execute my AJAX data retrieval function in the code:

if (typeof(info) === 'string'){
// If there's a URL, retrieve the data and add it to the datastore object.
    datastore.info = getINFO(info, asyn_return).then(data =>{
      console.log(data);
      return data;
    });
    //console.log(datastore.info);
} else {
    datastore.info = "";
}

console.log(datastore.info);

console.log(data) displays the expected data, but datastore.info remains empty:

{item1: "data", item2:"data", info: {} }

I'm unsure of what I might be overlooking technically for this to not result in the desired outcome.

After obtaining the promise (the wrapper), what triggers its resolution? And if that isn't happening, what could the probable issue be?

A big thanks to anyone willing to offer assistance.

Answer №1

Your console.log at the end is assuming that the information arrives synchronously, but it is actually asynchronous. This is why it is showing as undefined because the ajax data has not yet been received.

To fix this issue, you will need to modify your code to make it asynchronous. You can achieve this by using promises or async/await. Here's an example of how you can rewrite your code:

function fetchData(source) {
  return new Promise(resolve => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', source);
    xhr.responseType = 'document';
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var text = xhr.responseXML.getElementsByTagName('pre')[0].innerHTML;
        console.log(text);
        resolve(text);
      }
    };
    xhr.send();
  });
}

if (typeof info === 'string') {
  // If a URL is provided, fetch the data and store it in the datastore object.
  fetchData(info).then(data => {
    console.log(data);
    datastore.info = data;
    // Continue with your asynchronous code here
  });
} else {
  datastore.info = '';
}

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

Exploring the Reach and Sequence of AJAX Callbacks

This particular piece of code aims to achieve three main tasks: 1) validate the online status of users, 2) retrieve their information from a slightly different URL, and 3) present both sets of data in HTML format. The implementation appears functional bu ...

Ways to convert asynchronous operations of Node.js into synchronous operations in Node.js

Using node js, I am making multiple AWS API calls within a for loop. var prodAdvOptions = { host : "webservices.amazon.in", region : "IN", version : "2013-08-01", path : "/onca/xml" }; prodAdv = aws.createProdAdvCli ...

The Upstash Redis scan operation

Attempting to utilize the @upstash/redis node client library for Node.js (available at https://www.npmjs.com/package/@upstash/redis), I am facing challenges in executing the scan command, which should be supported based on the documentation. Specifically, ...

Adding a div via an Ajax call is only successful during the initial page load

Currently, I am utilizing a combination of YQL and jQuery to retrieve content from a distant page. While I am able to successfully load the content during the initial page load, I encounter an issue when attempting to return to the same page after navigati ...

How can I use JavaScript to show a div upon clicking an input element?

I am looking to make a block div visible when an input field is clicked. <input class="indifferent" type="radio" name="decision" value="indifferent"> Indifferent </br> <div class="input" style="display: none;"> Please assist with our com ...

URL not receiving AJAX request

I encountered an issue while attempting to send an ajax request to a specific URL in order to receive a JSON response. However, the request does not appear to be going to /login as expected. Instead, it remains on the current URL and appends the formData p ...

A guide on how to use Javascript to take a screenshot of an entire webpage

When a user triggers a script, it injects JavaScript code into the current page to make DOM changes. After interacting with the page, the user may want to save their modifications for later viewing or editing. However, if the original page source is edited ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

Tips for manipulating bits 52-32 within Javascript code, without utilizing string methods

Here is my functional prototype code that is currently operational: function int2str(int, bits) { const str = int.toString(2); var ret = ''; for (var i = 0; i < (bits - str.length); ++i) { ret += '0'; } re ...

Display components created for children above the components created for parents

I am looking to render a component with a different route without it covering the entire page. For example, let's say I click on a question from a list on Stack Overflow, and then I want an animated modal to appear from right to left without changing ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

What could be causing the code to not wait for the listener to finish its execution?

I've been attempting to make sure that the listener has processed all messages before proceeding with console.log("Done") using await, but it doesn't seem to be working. What could I possibly be overlooking? const f = async (leftPaneRow ...

Executing a PHP function within the same file using AJAX: A step-by-step guide

I've been exploring online tutorials to learn about ajax as it's a new technology for me. My main goal is to understand how to utilize two functions, create() and population(), in a php file. The create() function generates a form like this: ma ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

What is the best way to update information in the `App` component using Vue?

Within Vue, I have an App component that utilizes the <router-view> to extend the functionality of a Login component. My goal is to update specific data within the App component when a button is clicked in the Login component. Is this type of inter ...

"Enhance your website with the ability to dynamically load and display

I am facing a little issue and need suggestions because I am struggling with inserting data into an HTML page using the append jQuery function and AJAX request. Within my HTML block, under ul elements, there are some images that I directly insert into the ...

Preventing jquery from continuing its execution after an event has been successfully handled

I am experiencing an issue with a radio button that triggers a jQuery script upon clicking. The script is supposed to render a form where users can enter a comment. Everything seems to be working fine, the event is detected and the form is rendered, but wh ...