Richlewis
Richlewis

Reputation: 15374

Dealing with results from a Promise

I have a single node-fetch call which I am able to get a response from and successfully write the JSON to a file

fetch(`${BASE_URL}/leagues?api_token=${AUTH_TOKEN}`, { headers: headers })
.then(function(response){
  return response.json(); // pass the data as promise to next then block
})
.then(function(json){
  writeToFile('/path/to/file', json);
})
.catch(function(error) {
  console.log(error);
});

// Write to file function
function writeToFile(fileName, json) {
  fs.writeFile(fileName, JSON.stringify(json, null, 2), 'utf8', function (err) {
    if (err) {
      return console.log(err);
    }
    console.log("The file was saved!");
  });
}

I seem to be getting tripped up though when using Promise.all and wanting to write each response to file, this is what I have so far

var promise_array = [fetch(`${BASE_URL}/leagues?page=2&api_token=${AUTH_TOKEN}`), fetch(`${BASE_URL}/leagues?page=3&api_token=${AUTH_TOKEN}`), fetch(`${BASE_URL}/leagues?page=4&api_token=${AUTH_TOKEN}`)];

Promise.all(promise_array)
.then(function(results){
  // results are returned in an array here, are they in order though ?
  return results
})
.then(function(results){
  results.forEach(function(r){
    console.log(r.json())
  })
})
.catch(function(error){
  console.log(error)
})

As I'm trying to log out the JSON I get this returned in the console

> Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
 members: [] } }

I thought that the promise is fulfilled within the first then. What is happening here?

Upvotes: 1

Views: 1126

Answers (1)

Jerome WAGNER
Jerome WAGNER

Reputation: 22422

r.json() is a Promise (which is what you see in the log).

Beeing resolved or not, to get the value corresponding to the Promise, you have to use then

r.json().then(function(json) { console.log(json); })

Upvotes: 5

Related Questions