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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why do you have to put the return in front of the fetch?
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.
Well, I was returning data by: return flattenDeep(ChattersPerRole);, no?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.