繁体   English   中英

返回由promise.all()填充的数组

[英]Returning an array populated by promise.all()

我已经与Promise.all一起使用api调用构造了数组“ newPlanets”

export function api_calling(){
  var newPlanets = [];
  const URLs = fetching() // function that returns an array of fetches
  Promise.all(URLs).then(data => {
    // push all "results" field into newPlanets
    for (var i = 0; i < 7; i++) {
      for (var n = 0; n < 10; n++) {
        newPlanets.push(data[i].results[n]);
      }
    }
  })
  return newPlanets;
}

但是,将其返回到另一个调用它的函数时:

class App extends Component {
  constructor(props){
    let data = api_calling()
    console.log(data)
    super(props);
  }
}

控制台显示一个空数组。 如何将构造的数组返回到我的组件中?

承诺将异步解析,因此您不能在构造函数中编写let data = api_calling()

你可以改为返回的结果Promise.allapi_calling和设置组件的状态时,它在解决了componentDidMount

function api_calling() {
  const URLs = fetching();

  return Promise.all(URLs).then(data => {
    var newPlanets = [];

    for (var i = 0; i < 7; i++) {
      for (var n = 0; n < 10; n++) {
        newPlanets.push(data[i].results[n]);
      }
    }

    return newPlanets;
  });
}

class App extends Component {
  state = { data: [] };

  componentDidMount() {
    api_calling().then(data => {
      this.setState({ data });
    });
  }

  render() {
    // ...
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM