Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获得[[承诺价值]]';如果.then()不';不行吗?_Javascript_Reactjs_Promise - Fatal编程技术网

Javascript 如何获得[[承诺价值]]';如果.then()不';不行吗?

Javascript 如何获得[[承诺价值]]';如果.then()不';不行吗?,javascript,reactjs,promise,Javascript,Reactjs,Promise,情况是:我有一个城市数组,函数getCityForecast,它获取每个城市的预测,并将收到的转换数据返回到所需的格式。我需要将它们保存到数组中,并将此数组保存在组件的状态中 this.state = { cities: [ 'Санкт-Петербург', 'Москва', 'Казань', 'Самара', 'Красноярск', 'Чита', 'Чел

情况是:我有一个
城市
数组,函数
getCityForecast
,它获取每个城市的预测,并将收到的转换数据返回到所需的格式。我需要将它们保存到数组中,并将此数组保存在
组件的
状态中

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
    }
  }
在案例二中,我得到:

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

如何获得案例一的
[[PromiseValue]]
内容?

您应该将
呈现
设置为异步函数,并
等待承诺:

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))
实际上什么都不做–您只是将承诺中的值映射到它本身


另请参见“如果<代码>那么<代码>不起作用”是什么意思?您所处的情况有点不清楚。我认为稍微重构一下代码不会有什么坏处。首先,让我们将
getForecastData
作为一个函数,它实际返回获取的数据,而不返回任何其他内容,并将react/jsx代码从它移动到一个新函数,该函数可能称为
renderCities
。然后我假设您可以将城市数据存储在状态中,并使用
renderCities
?相应地渲染它。然后()
处理程序以级联方式执行,它们与
switch
语句的情况不同。一个
.then()
处理程序返回的值是下一个
.then()
处理程序的参数
.then(promiseResp=>(promiseResp))
是不可操作的。它只返回它接收到的值。Super noob
wait
/
async
问题。。。您需要在这里的某个地方使用
返回按钮吗?或者是自动处理的?@apsillers
renderCities
创建了一个无条件的承诺(
undefined
),它不会返回任何东西。传递给
map
的arrow函数有其通常的隐式返回。
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
    }
  }