如果.then()没有成功,如何获得[[PromiseValue]]的内容?

时间:2018-05-17 18:01:44

标签: javascript reactjs promise

情况是:我有一个cities数组,函数getCityForecast可以获取每个数据的预测,并将收到的转换数据返回到所需的格式。我需要将它们保存到数组中,并将此数组保存在state的{​​{1}}中。

component

所以问题在于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) 我得到了:

CASE TWO

如何获取__proto__: Promise [[PromiseStatus]]: "pending" [[PromiseValue]]: undefined CASE ONE内容?

1 个答案:

答案 0 :(得分:1)

你应该使renderCities成为异步函数,await作出承诺:

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))并没有真正做任何事情 - 你只是将承诺中的价值映射到自身。

另见How to access the value of a promise?