javascript - 在循环中正确使用 Promise javascript
问题描述
我正在尝试编写代码,使我能够按顺序从 API 获取数据并打印出我收到的内容。我有一本字典,其中包含美国各州的字典,其值是城市字典:城市代码对
var cities_forecast_dict = {'Alabama': {'Montgomery':''}, 'Alaska': {'Juneau': ''}, 'Arizona': {'Phoenix': ''}, 'Arkansas': {'Little Rock': ''},
'Connecticut': {'Hartford': ''}, 'Delaware': {'Dover': ''}, 'Florida': {'Tallahassee': ''}, 'Georgia': {'Atlanta': ''},
'Indiana': {'Indianapolis': ''}, 'Kentucky': {'Frankfort': ''}, 'Maine': {'Augusta': ''}, 'Maryland': {'Annapolis': ''}, 'Massachusetts': {'Boston': ''},
'Mississippi': {'Jackson': ''}, 'New Hampshire': {'Concord': ''}, 'New Jersey': {'Trenton': ''}, 'New York': {'Albany': ''}, 'North Carolina': {'Raleigh': ''},
'Ohio': {'Columbus': ''}, 'Pennsylvania': {'Harrisburg': ''}, 'Rhode Island': {'Providence': ''}, 'South Carolina': {'Pierre': ''}, 'Tennessee': {'Nashville': ''},
'Vermont': {'Montpelier': ''}, 'Virginia': {'Richmond': ''}};
我的代码应该从 Accuweather API 获取位置数据,以便每个城市各自的州应该有一个代表其唯一 id 代码的值。问题是,每当我尝试打印出cities_forecast_dict
我第一次创建它时的默认值时,我都会得到它的默认值。换句话说,每个城市的价值都只是''
. 我很确定这是因为 for 循环与我的主代码不同步。其他人说,当在循环中使用 Promise 时,应该创建返回 Promise 的方法,然后迭代这些方法并将每个返回的值推送到一个数组中,在该数组上.all()
可以调用该方法以确保每个 Promise 都有效,但这并不适用我。如果你不能告诉我,我是一个承诺的菜鸟。
intialize_location_id()
.then(console.log(cities_forecast_dict));
function intialize_location_id(){
for(state of Object.keys(cities_forecast_dict)){
for(city of Object.keys(cities_forecast_dict[state])){
var country_id = ''
var state_local_name = ''
fetch('http://dataservice.accuweather.com/locations/v1/cities/US/search?apikey=8iaBpn2Bl4GZtA9cgdXZT0dtpW30DGiB&q=' + city)
.then(response => response.json())
.then(loc => {
country_id = loc[0]['Country']['ID']
state_local_name = loc[0]['AdministrativeArea']['LocalizedName']
if (country_id == 'US' && state_local_name == state){
cities_forecast_dict[state][city] = loc[0]['Key']
}
else{
console.log('error! ' + loc[0]['Country']['ID'] + ' or ' + loc[0]['AdministrativeArea']['LocalizedName']+ 'or'+ city+ ' is not in the dictionary')
}
})
.then(res =>{
//intialize_forecast_data(state, city);
})
}
}
}
解决方案
不需要在这里使用循环,Promise.all
是你的朋友。
async function getMyResults () {
const cities = ['Montgomery', 'Juneau'];
const promises = cities.map(city => `http://dataservice.accuweather.com/locations/v1/cities/US/search?apikey=8iaBpn2Bl4GZtA9cgdXZT0dtpW30DGiB&q=${city}`).then(res => res.json());
const results = await Promise.all(promises);
}
推荐阅读
- c# - 使用 c# 将所有文件夹项添加到存档中
- node.js - 无法从发布请求中检测到字符串中的 \n 字符
- html - 如何在 crontab 脚本中加粗第一行 HTML
- matlab - matlab 从 GUI 按钮运行脚本文件
- angular - 角度显示页面顶部视图
- kendo-ui - 无法从 Kendo Combobox 中获得价值
- python - 类型为“object”时“super()”的行为?
- angular - 无法使用 pdfjs 库在 Ionic3 中呈现 pdf
- ios - 根据之前的 UITextView 内容向上调整 UILabel 位置?
- java - onCreateOptionsMenu 已定义