1

I'm trying to understand promises better and have implemented code that basically looks like this:

console.log(getRemoteData())

function getRemoteData (){
  return fetch('http://w.x.y.z')
  .then(response => {
    return response.json();
  });
}

Assuming that getRemoteData() returns a promise, how do I access the value of that response? I've tried to resolve the promise before logging to the console and I can't get it to do anything but log the promise obj. I think I'm missing a fundamental component of how promises work.

I've tried searching SO and all the answers I find point to a //do something with the returned data comment in the .then() method but I'd like to learn what I should do from there. The returned value is an array[].

Zach B
  • 534
  • 7
  • 25

2 Answers2

1

fetch(...) returns a promise, and response.json() returns another promise.

The returned value is not an array but a promise of an array. It should be:

getRemoteData().then(result => {
  console.log(result);
});

The structure can be flattened similarly to synchronous code in async functions (ES2017). They are syntactic sugar for promises, this snippet is equal to the previous one:

(async () => {
    const result = await getRemoteData();
    console.log(result);
})();
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Ahh, this is incredibly helpful, thanks! Is there a reason why I can't `return result` to the outer `console.log()` call instead of doing so within the returned promise? – Zach B Dec 07 '17 at 04:13
  • Because getRemoteData is asynchronous, and there's no result at the moment when it's called. See http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call for some ideas, it covers a lot of things including promises. – Estus Flask Dec 07 '17 at 04:16
1

Or use co if you are still on ES2015

var co = require('co');

co(function *(){
    // yield any promise
    var result = yield getRemoteData();
}).catch(onerror);
Yu-Lin Chen
  • 559
  • 5
  • 12