javascript - 如何使用 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)
};
解决方案
数组仍然是空的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);
})
推荐阅读
- jenkins - 愿意在代理列表上运行清理脚本,而无需为每个代理创建单独的阶段
- c - 从一个寄存器读取某些位并写入另一个寄存器的某些位
- python - 无法使用 os.environ 声明环境变量
- python - 在python中通过唯一列表创建标志
- c# - 为什么我的射弹游戏对象不移动?
- c - Doxygen 将 .c 和 .h 合并为一个模块
- c# - 用matblazor中的组件填充mat-layout-grid-cell
- python - 如何从以前的正则表达式结果中查看字符串
- algorithm - 使用 omega 作为最坏情况运行时间而不是 O
- linux - 检测到 USB 驱动器但无法在 linux 中的任何位置显示