I'm trying to fetch data from several urls stored in an array. Each url contains data in json format. I'm using a for loop to iterate over the urls stored in the url array. Each json file contains the travelTimeInSeconds value I'm interested in. When running the following code, the two values stored in the timeT variable are logged in the console. However, the ttTimes array remains empty. How do get the values to be stored in the ttTimes array?
urls = ['www.a.com/dataa.json','www.b.com/datab.json']
ttTimes = []
function getData(url) {
fetch(url)
.then(response=>{
return response.json()
})
.then(data =>{
let timeT = Math.round(data['routes'][0]['summary']['travelTimeInSeconds']/60);
console.log(timeT)
ttTimes.push(timeT)
})
}
for (url in urls){
time = getData(urls[url])
console.log(time)
ttTimes.push(time)
};
getDatadoesn't return anything 2.fetchis async, so even if you fix (1),timewill contain a Promise, nottimeT(which also isn't returned inside the callback) 3. to run multiple async functions, usePromise.all(this will return an array containing the results, exactly what you're looking for: jsfiddle.net/khrismuc/41axsLw6ttTimes; but: while this works in theory, the requests runs at the same time and will finish a) in an unspecified order b) at some point in the future, long after theconsole.log(ttTimes)you probably have in your code somewherettTimesto be used in another function instead of just logging it to the console?ttTimeshas been set. Once you enterasync, you cannot leave again. The idea is to put everything insidemain, in order, and useawaitfor async stuff. That way you can write "synchronous" code. I changed the above fiddle to show what I mean.urlsarray that allowsttTimesto be returned and used in a new function?