0

I kind of got the same question as has been asked here.

I've made a function:

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}`);
  });
};

Why can't I assign that return value to my variable? The log of that variable returns undefined...

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

Bonus question, how could I easily wait for viewersPerRole to be filled with the data I'm waiting for because of the fetch? (so I don't have to use setTimeout())?

Community
  • 1
  • 1
Kevin
  • 1,219
  • 1
  • 16
  • 34

1 Answers1

0

First of all, try returning something from the main function. There's no return in front on the fetch(...). Code should look like:

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))

If you're using Babeljs to transpile with stage3 enabled, have a look at async / await.

motanelu
  • 3,945
  • 1
  • 14
  • 21
  • Why do you _have_ to put the return in front of the fetch? – Kevin Oct 15 '16 at 21:51
  • You need to return a value that will be the result of calling rewardStayingViewersOrNewcomers(). If you don't do that, the result will be undefined. – motanelu Oct 15 '16 at 21:53
  • Well, I was returning data by: `return flattenDeep(ChattersPerRole);`, no? – Kevin Oct 15 '16 at 22:01
  • That was being *to* the rewardStayingViewersOrNewcomers() not *from*. If you do `let foo = fetch() ...` then foo was the result of `return flattenDeep(ChattersPerRole);`. Not if you want to have a return value from the rewardStayingViewersOrNewcomers() function, you just need to `return foo;` at the end. I just cut the middle man and returned it directly. – motanelu Oct 15 '16 at 22:04