gpt4 book ai didi

javascript - 如何获取[[PromiseValue] ]'s content if .then() doesn' t计算?

转载 作者:行者123 更新时间:2023-12-03 01:51:25 25 4
gpt4 key购买 nike

情况是:我有一个城市数组,函数getCityForecast获取每个城市的天气预报,并将接收到的转换后的数据返回为所需的格式。我需要将它们保存到数组中,并将该数组保存在组件state中。

this.state = {
cities: [
'Санкт-Петербург',
'Москва',
'Казань',
'Самара',
'Красноярск',
'Чита',
'Челябинск',
'Оренбург',
'Ростов-на-Дону',
'Орск'
],

cityObjects: []
};

this.getCityForecast = this.getCityForecast.bind(this);
this.renderCities = this.renderCities.bind(this);
}

getForecastData = async (cityKey, cityName) => {
const apiKey = 'ExAmPlEkEy';
const forecastUri = 'http://dataservice.accuweather.com/forecasts/v1/daily/1day/';
const uriToFetch = `${forecastUri}${cityKey}?language=ru&metric=true&details=true&apikey=${apiKey}`;
try {
let response = await fetch(uriToFetch);
if(response.ok) {
let jsonResponse = await response.json(); // Converts into JSON
if (jsonResponse.DailyForecasts) {
let cityData = jsonResponse.DailyForecasts.map(forecast => ({ //Data converted here into a convenient object
icon: forecast.Day.Icon,
iconPhrase: forecast.Day.IconPhrase,
tempValue: forecast.Temperature.Maximum.Value,
tempUnit: forecast.Temperature.Maximum.Unit,
cityKey: cityKey,
cityName: cityName
})
);

let renderCity = cityData.map(city => ( // Presented in React.js manner
<div
className="weather"
key={city.cityKey}>
<h1>{city.cityName}</h1>
<img
src={`http://apidev.accuweather.com/developers/Media/Default/WeatherIcons/${city.icon}-s.png`}
alt={city.iconPhrase}
className="weathericon" />
<h2>{`Температура: ${city.tempValue}°${city.tempUnit}`}</h2>
</div>
)
);

return renderCity; // Retuns a formatted city forecast
} else {
return [];
}
}
throw new Error('Forecast request failed!');
} catch (error) {
console.log(error);
}
}

renderCities = () => { // applies this.getCityForecast() to the array of city names
if(this.state.cities) {
const cityObj = Promise.all(this.state.cities
.map(city => this.getCityForecast(city)))
.then(promiseResp => (promiseResp)) // CASE ONE
/*.then(val => (val))*/ // CASE TWO <-- Not the above promise's value
.catch(e => {console.log(e)});
console.log(cityObj); // Save response to this.cityObjects
}
}

所以问题是在CASE ONE中它返回:

_proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(2) // <-- I need this content
0: [{…}]
1: [{…}]
length: 2
__proto__: Array(0)

案例二中我得到了:

__proto__: Promise
[[PromiseStatus]]: "pending"
[[PromiseValue]]: undefined

如何获取CASE ONE[[PromiseValue]]内容?

最佳答案

您应该将 renderCities 设为异步函数并等待 promise :

renderCities = async () => { // applies this.getCityForecast() to the array of city names
if(this.state.cities) {
const cityObj = await Promise.all(this.state.cities
.map(city => this.getCityForecast(city)))
.catch(e => {console.log(e)});
console.log(cityObj); // Save response to this.cityObjects
}
}

.then(promiseResp => (promiseResp)).then(val => (val)) 并没有真正做任何事情 - 你只是映射对自身的 promise 中的值。

另请参阅How to access the value of a promise?

关于javascript - 如何获取[[PromiseValue] ]'s content if .then() doesn' t计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50397852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com