2017-02-14 77 views
0

我想返回由函數getData()獲取的數據並使用返回的值(return this.getStreamer(values[0],values[1]);)來呈現StreamerContainerResult組件。我想獲取數據返回某個值的函數

然而,它保留返回「不確定」,因此,我不能使任何東西..

我被困在這個bug在過去的幾個小時,我無法弄清楚我自己。

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

回答

0

您正在嘗試從asyncronous回調函數中返回數據。因此,信息不會被訪問。請參閱以下有關回撥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是關於如何使用回調工作的一些很好的閱讀。

+0

謝謝。我成功地訪問了函數返回的元素。但是,由於某些原因,它仍然不會被組件渲染。爲什麼? – brood915

+0

你正在使用reactJS呃?我不太瞭解它..但也許這[問題](http://stackoverflow.com/questions/24185029/reactjs-async-wait-for-results)將有所幫助。乾杯。 – matt