将函数的返回值赋给变量

时间:2016-10-15 20:59:20

标签: javascript

我得到了与被问及here相同的问题。

我做了一个功能:

const rewardStayingViewersOrNewcomers = () => {
  fetch('https://tmi.twitch.tv/group/user/instak/chatters')
  .then(parseJSON)
  .then(r => {
    let chatters = r.chatters;
    viewerKeys = Object.keys(chatters); // [mods, viewers,...]
    let ChattersPerRole = viewerKeys.map(role => {
      return chatters[role].map(username => ({
        username, role
      }));
    });
    return flattenDeep(ChattersPerRole);
  }).catch(err => {
    console.log(`Error in fetch: ${err}`);
  });
};

为什么我不能将该返回值分配给我的变量?该变量的日志返回undefined ...

let viewersPerRole = rewardStayingViewersOrNewcomers();
setTimeout(() => console.log(viewersPerRole), 7000);

奖金问题,我怎么能轻易地等待viewersPerRole被我正在等待的数据填充? (所以我不必使用setTimeout())?

1 个答案:

答案 0 :(得分:0)

首先,尝试从main函数返回一些东西。在获取(...)前面没有返回。代码应如下所示:

const rewardStayingViewersOrNewcomers = () => {
  return fetch('https://tmi.twitch.tv/group/user/instak/chatters')
  .then(parseJSON)
  .then(r => {
    let chatters = r.chatters;
    viewerKeys = Object.keys(chatters); // [mods, viewers,...]
    let ChattersPerRole = viewerKeys.map(role => {
      return chatters[role].map(username => ({
        username, role
      }));
    });
    return Promise.resolve(flattenDeep(ChattersPerRole));
  }).catch(err => {
    console.log(`Error in fetch: ${err}`);
  });
};

// now that you're returning a promise
rewardStayingViewersOrNewcomers()
  .then(viewersPerRole => console.log(viewersPerRole))

如果您在启用stage3时使用Babeljs进行转换,请查看async / await。