-1

This is a silly question but can you explain what is wrong with this code? Why can't I perform this?

const fetch = require('node-fetch');

const fetchProm = (() => {
    return fetch('https://api.github.com/users/github');
}).then((response) => {
    return response.json();
}).then((json) => {
    console.log(json)
});
  • The json u r getting in the end can be assigned to a variable, so that u can use it later. To read more about promises https://mdn.io/promise –  Jul 15 '18 at 11:28
  • Instead of console.log you should return the JSON, then it would have it’s value... (if you call the function) – Akxe Jul 15 '18 at 11:29

1 Answers1

1

Declaring a function is not the same as calling one

You are not calling the function that returns the promise, just declaring it. You'll need to add an additional set of parentheses before the first .then() in order to actually call the function:

const fetch = require('node-fetch');

const fetchProm = (() => {
    return fetch('https://api.github.com/users/github');
})().then((response) => {
    return response.json();
}).then((json) => {
    console.log(json)
});

If you want to call everything at a later time, you need to place the whole thing in its own function where the promises get handled in an isolated scope:

const fetch = require('node-fetch');

const fetchProm = () => {
    fetch('https://api.github.com/users/github')
    .then(response => response.json())
    .then(json => console.log(json));
};

fetchProm();
Sam Holmes
  • 1,594
  • 13
  • 31
  • Thank you very much for your detailed answer! I guess there is no way to have a chain of promises declared under a single variable and I have to break them down, is this correct? – νόου μπάντυ Jul 15 '18 at 11:43
  • Sorry to keep doing this, I've actually just added a little bit that puts the whole thing in a singular function! – Sam Holmes Jul 15 '18 at 11:44
  • 1
    Why would you not just do `fetch(...).then(...)` here? What does the wrapping function add? – lonesomeday Jul 15 '18 at 12:01
  • I assumed all that was wanted was an isolated context. I believe the initial misunderstanding was @νόουμπάντυ thinking that calling the `fetchProm()` method would _automatically_ call all subsequent chained promises. – Sam Holmes Jul 15 '18 at 12:03