0

I am trying to get an array from my mongodb database, but am having problems setting the array to a variable to use in another function. I am calling the below method from another method that creates a table from the information from the database, but when I call this function it returns after the req.send() is called, not at the end of the function. So cart is empty since it does not wait to receive the response, it just returns to the function I am calling getFromAPI() from. Any advice would be greatly appreciated. Thanks!

function getFromAPI() {
  var req = new XMLHttpRequest();
  req.open('GET', '/products');
  req.setRequestHeader('Content-Type', 'application/json');
  req.send();
  req.addEventListener('load', () => {
    console.log(req.responseText);
    var cart = req.responseText;

  });
  req.addEventListener('error', () => {
    console.log('There was an error');
    console.log(error);
  });
}


Emma
  • 13
  • 2

1 Answers1

0

You can use promises when dealing with asynchronous operations. More details can be found here.

The code above can be changed to the following...

function getFromAPI() {
    return new Promise(function (resolve, reject) {
        var req = new XMLHttpRequest();
        req.open('GET', '/products');
        req.setRequestHeader('Content-Type', 'application/json');
        req.onload = resolve;
        req.onerror = reject;
        req.send();
    });
}

You can then invoke the previous function as such...

getFromAPI()
    .then(function (e) {
        // perform some action on success. add items to cart, etc.
        console.log(e.target.response);
    }, function (e) {
        // handle errors
    });