【问题标题】:Returning a value in a Promise在 Promise 中返回一个值
【发布时间】:2018-10-06 22:08:30
【问题描述】:

我正在尝试返回一个字符串值以在我的 HTML 中显示它。在我的 HTML 中,我在 View 中使用 Text 元素(类似于 React Native 中的 div),并尝试用我从方法 _getCategories 中获得的内容填充它。问题是我不能让该方法返回一个字符串值,因为该值是在 Promise 中返回的。

现在,我试图让这个方法返回一个简单的字符串值:

    _getCategories = item => {
    const categoryNames = [];
    let fetches = [];
    var allCategories = '';
    for (var i = 0; i < item.categories.length; i++) {
      allCategories = allCategories + item.categories[i] + ',';
    }
    allCategories = allCategories.substring(0, allCategories.length - 1);
    fetches.push(
      fetch(
        'http://54.168.73.151/wp-json/wp/v2/categories?include=' + allCategories
      ).then(response =>
        response.json().then(responseJson => {
          var names = '';
          for (let category of responseJson) {
            names = names + category.name + ', ';
          }
          this.names = String(names.substring(0, names.length - 2));
          console.log(this.names);
          return <Text style={styles.categories}>{this.names}</Text>;
        })
      )
    );
  };

我认为这已经返回了正确的值,但它没有显示在我的视图中。我把上面的方法调用如下:

<View>
      {this._getCategories(item)} //this will be a text element after return
</View>

编辑:

我通过只对所有类别一起发出一个请求来简化我的代码,因此它现在可能应该返回一个 Text 对象。不幸的是,我的应用程序中仍然没有显示文本。

【问题讨论】:

  • Promise.all 返回另一个promise,因此您的整个函数仍然返回一个可以解析为您的字符串的promise。
  • 其实我的错,它没有返回任何东西,因为你没有返回 Promise.all

标签: javascript json promise


【解决方案1】:

首先从方法中返回promise链:

 return Promise.all(fetches).then(res => {

但是它仍然返回一个 promise resolve somewhen 到一个文本,并且没有办法改变它。相反,文本应该是组件状态的一部分,以便 xou 可以在 promise 解决时更新文本:

  onComponentDidMount() {
    this._getCategories().then(categories => this.setState({ categories }));
 }

render() 里面做:

 <div>
  {this.state.categories || <Text>Loading categories</Text>}
 </div>

【讨论】:

  • 我现在更新了我的代码,但它似乎在 _getCategories 方法的第一个 for 循环中给了我一个错误,说 item.categories 未定义。
  • @MJM 是的,你仍然必须以某种方式传递item ......并且请不要编辑问题的答案,这会让更多观众难以理解你的问题......
  • 这次我只简化了我的代码(请看我的编辑)。你明白为什么没有正确返回所需的对象吗?我现在摆脱了 Promise.all 部分。
猜你喜欢
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 2014-10-21
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
相关资源
最近更新 更多