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