0

How to get array that is located on PromiseValue instead of getting Promise {<pending>} While I'm using .then(data => console.log(data)) I'm getting array in console log. However, I need to get an array to place it on the html page so I changet code to .then(data => data) and started to get 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);

Thanks in advance.

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey May 29 '20 at 13:12

2 Answers2

-1

I think you will have to return the value of data as mentioned here to complete the promise

When promise returned by sendRequest is resolved, it will immediately pass a new promise to getData .

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

looks something like this

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 
})

Have a look at this question

user1207289
  • 3,060
  • 6
  • 30
  • 66
-1

sendRequest() will execute async. This means that the script continues, even though the data is not loaded. So the last line console.log(getData) will already happen before any of the data is loaded.

This is what promises can be used for:

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

Another option would be to use async and await. But this does not work in older browsers.

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

let getData = await sendRequest('GET', baseUrl + '/users');
console.log(getData);
Joel'-'
  • 652
  • 1
  • 5
  • 17