0

I have code like this:

function fetchUsers(cb) {
    fetch(API_BASE + '/users/').then(checkStatus)
                               .then(parseJSON)
                               .then(cb);
}

If I pass cb so that it takes the JSON and stores it or applies it all is well.

What I would prefer is something like this:

function fetchUsers(cb) {
    return fetch(API_BASE + '/users/').then(checkStatus)
                                      .then(parseJSON)
                                      .then(data => { return data });
}

But this does not work because the returned data is still a Promise. There are several questions on SO about Promises and fetch. NodeJS fetch promise callback pending or Get the data from fetch -> promise -> response for instance. But I could not find one that explains why the work has to happen within the then call. Is there an idiomatic way to block until the Promise is resolved?

Sean Perry
  • 3,776
  • 1
  • 19
  • 31
  • `return fetch` this is always going to return promise. Is there any reason you can't just do `fetchUsers.then()`, If you want a blocking version of fetch, your only option currently is XMLHttpRequest, but even then it's rapidly been depreciated on the main thread. If you don't like callbacks & thenables, have a look at async / await, these work with Promises. – Keith Oct 01 '17 at 08:55
  • This was the point of my question. I cannot find an explanation of WHY this matters. How would `fetchUsers.then` be any different from what I posted?Why does the Promise have to be handled in a callback? – Sean Perry Oct 02 '17 at 17:58
  • Getting marked duplicate without a pointer is not helpful. I actually linked two questions which are similar but miss my question. – Sean Perry Oct 02 '17 at 17:59
  • `Why does the Promise have to be handled in a callback?` because the calling end would have to block otherwise, and that's bad. The best way to look like it's blocking is use asyn/await, but in the background it's just doing the thenables for you. – Keith Oct 02 '17 at 19:37
  • Thanks for the pointers @Keith. Sorry I can't give you points. – Sean Perry Oct 04 '17 at 18:38

0 Answers0