首页 > 解决方案 > 如何使用 for 循环将数据从 fetch() 推送到 Javascript 中的数组?

问题描述

我正在尝试从存储在数组中的多个 url 中获取数据。每个 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)
};

标签: javascriptarraysjsonfetchjavascript-objects

解决方案


数组仍然是空的ttTimes,因为在检查它之前你永远不会等待承诺解决。在检查结果数组之前,您可以使用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);
})

推荐阅读