Obtain information through ajax using an asynchronous function

When fetching data in the first example using ajax with XMLHttpRequest, everything works smoothly.

example 1

let req = new XMLHttpRequest();
req.open(
    "GET",
    "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json"
);

let res = {};
req.onload = () => {
    res = JSON.parse(req.responseText);
};

req.send();

window.onload = _ => {
    console.log(res);
};

However, I wanted to streamline and condense my code using the async function. Here is what I attempted:

example 2


async function res() {
    let req = new XMLHttpRequest();
    req.open(
        "GET",
        "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json"
    );

    let res = {};
    req.onload = () => {
        res = JSON.parse(req.responseText);
    };

    req.send();
    return await res;
}

window.onload = _ => {
    console.log(res());
};

Unfortunately, it consistently logs the following in the console:

Promise {<pending>}

Answer №1

In order to utilize asynchronous functions, it is necessary to return a Promise.

An alternative method is to use the fetch function, which represents a more modern approach to fetching data.

For example:

const httpRequest = async () => {
    try {
        const response = await fetch('http://example.com/movies.json');
        return await response.json();
    } catch(e) {
        console.err(e);
    }
}

To address your issue, consider employing the following approach:

function request() {
    return new Promise((resolve, reject) => {
        let req = new XMLHttpRequest();

        req.open(
            "GET",
            "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json"
        );

        req.onload = () => {
            resolve(JSON.parse(req.responseText));
        };

        req.send();
    })
}

function res() {
    request().then(data => console.log(data));
}

window.onload = _ => {
    console.log(res());
};

Answer №2

Waiting for the data object that is currently empty in your code. Make sure to properly wait for the Promise. For example:

await request
result data

If this approach doesn't yield the expected result, consider using .then() method.

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 for automatically playing the next song when a button is clicked

I have encountered a challenge in developing a music player. The issue lies in the loading of the next song when the user clicks the 'next' button. While the new data is successfully updated in both the state and render, the music does not automa ...

Disable toolbar focus in TinyMCE

Is there a method to prevent the appearance of the white square known as "Focus to toolbar" in TinyMCE? Clarification: Upon pressing Alt+F10 in TinyMCE, a white square is outlined around a button on the toolbar. This allows navigation among toolbar butto ...

The issue arises when trying to escape double quotes within a regex pattern using ng-pattern

My ng-pattern validation includes a regex pattern ^[^\./:*\?\"<>\|]{1}[^\/:*\?\"<>\|]{0,254}$ to prevent invalid characters in file paths and set a limit. However, when I specify the ng-pattern as: ng-p ...

Displaying an RSS feed inside a designated div element

Seeking assistance from all you wonderful individuals for what seems to be a simple problem. Here is the HTML code I am working with: <div id="rssfeed"></div> Along with JavaScript that includes the FeedEK plugin $(document).ready(function ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

The Firebase function that reloads the auth currentUser is not refreshing properly within a Vue component

My function for updating the profile URL using the reload method is not reflecting changes in my computed property. Computed Property computed: { photoUrl: function() { return firebase.auth().currentUser.photoURL; }, } Function onFileC ...

Check the validity of multiple selection groups using JavaScript

Here is the link to my JS Fiddle: http://jsfiddle.net/m4tyC/ I am working with multiple select tags and need to validate them upon submission. For example, at least one of size1, color1, or Qty1 must be selected in the first group. If one item is selected ...

Perform a replacement with jQuery.replaceWith() on an input field and refocus in Microsoft Internet Explorer

There exists a script http://gist.github.com/457324 which establishes default text (extracted from the element's title attribute) for empty input[type=text] as well as input[type=password] elements. However, setting default text for password elemen ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Guide to sending and receiving JSON data using XAMPP PHP

Currently, my XAMPP 7.1.10-0 server is up and running with the following index.php file: <?php if(isset($_POST["username"])) { echo $_POST; header("Location:getbooks.php"); exit; } else { echo file_get_conten ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

Incorporating an HTML page into a dialog using AngularJS: A step-by-step guide

Is it possible to dynamically change the content of a dialog by updating the URL? I have multiple HTML pages that I want to display in my dialog by simply changing the URL. <md-button ng-click="showDialog($event,'myurl/page-1.html')">Show ...

Using the split and join methods in PHP for Javascript operations

Can you assist me with writing this code in PHP? I've attempted multiple times but I can't seem to get it right. Any help would be greatly appreciated! return s.split(/\r?\n/).join("<br>"); Thank you in advance! ...

unable to send updates to groups in socket.io

When a user connects, the system will search for a room with fewer people than the maximum allowed. If such a room is found, the user joins it. If no suitable room is available, the system creates a new one. The room creation process is functioning correct ...

Which types of characters am I allowed to include in an HTTP response body while using NodeJS and Express?

I am currently developing a node express app that responds to an AJAX post from the client browser. I am curious about what characters would be considered invalid to include in the HTTP response body. My response header specifies the use of charset=utf-8, ...

What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a fun ...

How to arrange three buttons in a row using CSS styling

After reviewing similar issues posted by others, I have not found a solution to my problem. Despite trying the suggested solutions, I am unable to center two buttons representing different departments on my webpage. Here is my source code: <script ...

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

Extension Overlay for Chrome

I'm currently working on developing a Chrome extension, but I'm encountering some confusion along the way. Despite researching online, I keep receiving conflicting advice and haven't been able to successfully implement any solutions. That&ap ...