Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use

.then(data => console.log(data))
, I can see the array in the console log. However, my requirement is to display this array on an HTML page. So, I modified the code to .then(data => data) and now it returns Promise {<pending>}

const baseUrl = 'http://localhost:3000';

function sendRequest(method, url, data = null) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open(method, url);

        xhr.responseType = 'json';
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = () => {
            if (xhr.status >= 400) {
                reject(xhr.response);
            } else {
                resolve(xhr.response);
            }
        }

        xhr.onerror = () => {
            reject(xhr.response);
        }

        xhr.send(JSON.stringify(data));
    });
}

let getData = sendRequest('GET', baseUrl + '/users')
.then(data => data)
.catch(err => console.log(err));

console.log(getData);

I appreciate any help with this issue.

Answer №1

When you use the function sendRequest(), it will execute asynchronously. This means that the script will continue running even before the data is fully loaded. As a result, the last line <code>console.log(getData)
will be executed before any data is actually loaded.

This is where promises come in handy:

sendRequest('GET', baseUrl + '/users')
    .then(function(data){
        // The response can only be processed in the .then part. 
        // You can also call other functions using the fetched data
        console.log(data);
    })
    .catch(err => console.log(err));

Another approach would be to use async and await. However, this method may not work in older browsers.

async function sendRequest(method, url, data = null) {
// your current xhr code
}

let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);

Answer №2

It appears that in order to fulfill the promise, you need to return the value of data, as indicated here.

Once the promise generated by sendRequest is resolved, a new promise will be immediately passed to getData.

.then(data => { 
      return data;
})
.catch (err => { 
      console.log(err);
})

This is similar to the following example:

function sendRequest(s){
  return new Promise((resolve, reject) => {
       resolve(s) ; 
  });
}

let getData = sendRequest("test")
 .then(value => {
    return value;
})

getData.then(value => {
    console.log( value);
    //access value 
})

You can refer to this question for more information.

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

Why would one utilize window.location?.search?.split?

Could someone explain the purpose of using window.location?.search?.split('=')[1] and why the value of id is set to window.location?.search?.split('=')[1]? Code: function EndScreen() { const [score, setScore] = React.useContext(Score ...

Inject a DOM event into a personalized form validator within an Angular application

I'm currently working on validating a form using the reactive approach. I've implemented a file input to allow users to upload files, with custom validation conditions in place. However, I'm encountering an issue where the validator only rec ...

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

Is it possible to include a value for the "src" attribute rather than the "class" attribute in the array of values in list.js?

Check out the HTML code I wrote: <html> <head> </head> <body> <input class="search" placeholder="Search" /> <div id="users"> <ul class="list"> ...

Trouble with unproductive downtime in ReactJS and JavaScript

I'm looking for a way to detect idle time and display a dialog automatically after a certain period of inactivity. The dialog should prompt the user to click a button to keep their session active. Currently, when the user clicks the button it doesn&a ...

Transmitting an array of objects via Ajax to PHP

Assistance Needed: I have created my object using the following code: var data = []; $("#report-container [id^='report-']").each(function(index) { var reportObject = { "subject" : "", "photo" : "", "rating" : "", ...

Switching icon images using JQuery based on state changes

I'm attempting to switch the background image of my webpage's "body" element when the user toggles between playing and pausing music icons. This is what the CSS for the "body" element looks like: body { background: url('https://s3-us-wes ...

Is it possible to include indices in a list of hashes when sending an Ajax request to the controller in JSON format?

When sending data to a Rails controller: $.ajax({ url: '/haha', type: 'put', dataType: 'json', data: { multiplication: [ { "a": 5, "b": 5 }, { "a": 5, "b": 5 ...

Error: Attempting to access an undefined property

I have a quite extensive Vue/Vuitify project that is not functioning correctly. I have simplified the project down to a small program to highlight the issue. Despite trying everything that comes to mind, and even some things that don't, I am unable to ...

Error in Next.js: Trying to destructure an undefined object in useContext

While attempting to change the state of my cursor in a Next.js app using useContext, I encountered the following error: TypeError: Cannot destructure 'Object(...)(...)' as it is undefined. The goal is to update the state to isActive: true when h ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

Sending JSON data from Flutter to a fresh Stateful Widget

After passing JSON data to a new stateful widget in Flutter, I encountered an issue where the widget was receiving null data despite seeing the data in the debug console. I have tried different methods of passing data types, but none seem to work. Can any ...

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

sending an array via xmlhttprequest

I am attempting to send all the marks entered by the user to another page for processing, but only the value of the first mark entered in the table is being sent. Is there a way to send all the values of the marks entered rather than just the first value ...

The designated redirection path, as indicated in the 'next.config.js' file for a particular project, has now been applied to all projects

Something strange is happening... I set a redirect path for the root index page in one of my projects and it worked perfectly, but now all of my other projects are also being redirected to that same path when I try to visit localhost:3000. It's alway ...

Angular's separate scope variables allow for isolated data manipulation within individual components

Struggling with one scope variable affecting multiple elements in a div in AngularJS. Looking for help as a beginner in handling this issue. For a clearer understanding, here's an example: JS: /* controller-home.js ********************************* ...

What is the syntax for referencing a nested dictionary within a Python dictionary?

This issue has been resolved successfully How can I access the topic key in the questions data structure? I want to filter my list for all questions with a specific topic and then retrieve all details about a random question. However, when executing the ...

Loop through a hash while my value keeps fluctuating with each iteration

Currently tackling a simple hash loop to manipulate JSON data. Here's the Json data snippet: { "polls": [ { "id": 1, "question": "Are you planning to use laundry/dry cleaning service at least twice a month?" }, { "id": 2, "question": "Have yo ...

Variable Returned by AJAX

I am attempting to send a variable using a select box via POST method, then use AJAX to submit the data and finally leverage that variable on the original page to update SQL queries. Below is the code snippet I currently have: <script type="text/j ...