我正在尝试从存储在数组中的几个URL中获取数据。每个网址都包含json格式的数据。我正在使用for循环遍历存储在url数组中的url。每个json文件都包含我感兴趣的travelTimeInSeconds
值。运行以下代码时,存储在timeT
变量中的两个值将记录在控制台中。但是,ttTimes
数组保持为空。如何获取要存储在ttTimes
数组中的值?
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)
};
ttTimes
数组保持为空,因为您从不等待对promise的解析,然后再对其进行检查。您可以使用Promise.all
等待所有命令,然后再检查结果数组。
urls = ['www.a.com/dataa.json','www.b.com/datab.json']
// This function just returns a promise
function getData(url) {
return fetch(url)
.then(response=>{
return response.json()
})
.then(data =>{
const timeT = Math.round(data['routes'][0]['summary']['travelTimeInSeconds']/60);
return Promise.resolve(timeT);
})
}
Promise.all(
// use the urls to create an array of promises
urls.map(getData)
).then((ttTimes) => {
// When all the promises have been resolved, then this will be executed
//Here all the promises have been resolved, so you would have an array with the ttTimes
console.log(ttTimes);
})