0

I'm trying to do something like this:

Promise.all(stocks.map(e=>{
  var url = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${e}&apikey=${process.env.API_KEY}`;
  var dataReq = new XMLHttpRequest();
  dataReq.open('GET', url, true);
  dataReq.send()
  return dataReq.onload=()=>Promise(function(){
    var rawData = JSON.parse(dataReq.responseText);
    var data = rawData['Time Series (Daily)'];
    var keys = Object.keys(data).sort((a,b)=>a-b);
    return data[keys[0]];
  }).then(data=>data)
}))
.then(data => {
  console.log(data);
})

I've tried wrapping both the dataReq.send() and the dataReq.onload() function in the new Promise(), I've tried wrapping the new Promise() in a function, and I've tried returning both the .onload(...).then(...) and the .send().then(...) (moving whichever one I'm returning to the last line). I've gotten the console output to yield [[Function], [Function]], but can't get it to display the actual data. The reason I want to wait till both sets of data have been retrieved is because I want to do a search against a DB for entries that fit the criteria in either data set, so I want to grab both sets of data first and then search the DB.

Tara
  • 389
  • 3
  • 14
  • 1
    For simplicity, start with writing a separate function for a single request only. Make sure that it returns a promise and that you can call `then()` on it and it works. See the duplicate for inspiration. Then, once you got that working, call the function from the `map`. – Bergi Nov 17 '19 at 04:28
  • @Bergi, cool, that worked! Thank you! ^^ – Tara Nov 17 '19 at 06:09
  • @Bergi I just have one more question...why do we need to write a function that returns a promise, why can't we just write the promise directly? (i.e. `new Promise(function(resolve, reject){/*async stuff*/}).then(data => {/*do stuff with data*/})` – Tara Nov 17 '19 at 07:19
  • You can do that, putting the `new Promise` stuff in a separate function is just cleaner. – Bergi Nov 17 '19 at 14:57

0 Answers0