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

Adjust the active carousel item to 0 within onsen-ui (displaying a list of carousel items in a sliding menu)

In my sliding menu, each menu item contains a carousel with two items. I am trying to make the first carousel item show after closing and reopening the menu, or by clicking a button outside of the list on the menu page. This is my current setup: <ons- ...

Intersection observer automatically removes images from carousel (Siema) after they have been viewed

Check out this example to see the issue I'm facing. I've implemented an intersection observer for lazy loading images, here's the code: const pictures = document.querySelectorAll("[data-src]"); function loadPicture(pic){ const src = p ...

Transferring files and information using the Fetch API

I am currently working on a React application and I have defined the state of my application as shown below: const [book, setBook] = useState({ title: '', cover: {} numberPages: 0, resume: '', date: date, }); The & ...

MongoDB has encountered an issue where it is unable to create the property '_id' on a string

Currently, I am utilizing Node.js and Express on Heroku with the MongoDB addon. The database connection is functioning correctly as data can be successfully stored, but there seems to be an issue with pushing certain types of data. Below is the database c ...

Angular 6 - The state of the expression was altered after it was verified, different types of constructions

During the build process in debug mode with ng build, I am encountering errors in some components. However, when I switch to production mode using ng build --prod, these errors disappear. I am curious as to why this discrepancy is occurring. Error: Expre ...

Using jQuery or Javascript to implement a drop-down list filter functionality

For the past two months, I've been struggling to figure out how to create a drop-down menu to filter content on the site I'm building for my boss. Despite countless searches online, I haven't found a solution that works. This is the only iss ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

Retrieve Next Element with XPath

I recently started working with XPATH and have a few questions about its capabilities and whether it can achieve what I need. The XML Document structure I am dealing with is as follows: <root> <top id="1"> <item id="1"> < ...

Looking for a foolproof method to determine if a string contains any of the elements in a given array of substrings? And if found, how

I am currently faced with the task of decoding multiple URLs, specifically focusing on encoded special characters like "+", "|", and more. My approach involves having a collection of encoded characters that I need to locate in the URL string. What is the ...

Tips for automatically closing one element when another is clicked

My goal is to create a menu that displays when I click on a link, and if another menu is already open, it should close before displaying the new one. Essentially, I want to achieve an accordion menu where only one menu is open at a time. However, despite m ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

Tips for transferring information from controller JavaScript to view JavaScript within AngularJS

Currently, I am working on an angularJS application where I retrieve data from a REST service within the controller. The retrieved data is then passed to the view using $scope. However, I encountered an issue when trying to use this data in my in-page Java ...

In what ways can I leverage the functionalities of an AngularJS directive to delay the display of content until a user clicks on it?

Our rental application utilizes an API call to populate an array, triggering an ngRepeat and generating a list of divs displaying basic rental property information. Upon clicking a specific property, another API call is made to populate an interior ngRepe ...

What steps should I take to address and resolve this problem with my Angular $scope?

One of my partials utilizes a single controller named CaseNotesCtrl. However, I am encountering difficulties accessing $scope variables within this partial. Below is the code snippet: <div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotes ...

Tips for refreshing views with Angular JS

I am looking to refresh all the views displayed on my page. The layout consists of a Header, Footer, and Body view. Within the Header view, there is a dropdown menu where users can choose their preferred language. Upon selecting a language, I want all the ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

Error: 'require' function is not recognized in the latest JavaScript file

I am interested in using anime.js. To install this library, I need to follow these steps: $ npm install animejs --save const anime = require('animejs'); The code should be written in a js file named "anime.js" Here is the code for "anime.js": ...

Covering the entire screen, the Div element takes up the entirety of

Just like with other pages, the main div always takes up the entire screen visible to the user. As they scroll down, another div becomes visible: example1 , example2 Regardless of the screen size, the main div will always fill the space visible to the use ...