首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我希望获取数据的函数返回一个特定值

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

Stack Overflow用户
提问于 2017-02-15 06:15:24
回答 1查看 64关注 0票数 0

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

但是,它一直返回"undefined“,因此,我无法呈现任何内容。

在过去的几个小时里,我被这个bug卡住了,我自己也搞不清楚。

代码语言:javascript
复制
 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

EN

回答 1

Stack Overflow用户

发布于 2017-02-15 06:24:10

您正在尝试从异步回调函数中返回数据。因此,这些信息将无法访问。下面是带有回调done函数和对this的引用的更新代码片段。干杯。

代码语言:javascript
复制
//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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42237267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档