我希望获取数据的函数返回一定的值

时间:2017-02-14 22:15:24

标签: javascript reactjs fetch

我正在尝试返回函数getData()获取的数据,并使用返回的值(return this.getStreamer(values[0],values[1]);)来呈现StreamerContainerResult组件。

然而,它一直在返回" undefined"结果,我无法渲染任何东西..

过去几个小时我一直在坚持这个错误,我不能自己解决这个问题。

 getData(value, type) {
    let streamerData = [];

    let urls = ['https://wind-bow.gomix.me/twitch-api/streams/' + value, 'https://wind-bow.gomix.me/twitch-api/users/' + value];

    const getJson = url => fetch(url).then(res => res.json());
    Promise.all(urls.map(getJson))
           .then((values) => {
             if (type === "search") {
               this.setState({
                 streamer: values
               });
               console.log("searching");
             } else {
               console.log("displaying");
               return this.getStreamer(values[0],values[1]);
             }
          }).catch(err => {
            console.log('Something went wrong...')
          });
} 

https://codepen.io/brood915/pen/OWQpmy?editors=0110

1 个答案:

答案 0 :(得分:0)

您正在尝试从异步回调函数中返回数据。结果,信息将无法访问。有关具有回调done功能的更新代码段以及对this的引用,请参阅下文。欢呼声。

//Notice I added a done callback for when our asyncronous function is finished
function getData(value, type, done) {
  //Added a variable that points to this (to have scope to our other functions)
  var self = this;

  let streamerData = [];

  let urls = ['https://wind-bow.gomix.me/twitch-api/streams/' + value, 'https://wind-bow.gomix.me/twitch-api/users/' + value];

  const getJson = url => fetch(url).then(res => res.json());

  //Due to the asyncronous nature of a promise, you cannot return information via a return. See below... 
  Promise.all(urls.map(getJson))
    .then((values) => {
      if (type === "search") {
        self.setState({
          streamer: values
        });
        console.log("searching");
      } else {
        console.log("displaying");

        //This return is the return for the function, it won't return the data
        // return self.getStreamer(values[0], values[1]);
        //Return by passing the data to the callback
        done(self.getStreamer(values[0], values[1]));
      }
    }).catch(err => {
      console.log('Something went wrong...')
    });
};

//Calling our function above.
getData("<value>", "<type>", function(streamer) {
  console.log(streamer); //This should contain the information you need.
})

Here是关于如何使用回调的一个很好的解读。