0

Using window.fetch() in Firefox and Chrome to get data from a local JSON file, is proving troublesome:

var url = "http://sandbox.ccchapel.com/Thy-Kingdom-Come/data/outreach-spree.json";
var request = new Request(url, {
        method: 'get',
        mode: 'no-cors'
    });

fetch(request).then(function(response) { 
    console.log(response);
    return response.json();
}).then(function(j) {
    console.log(j);    
});

For whatever reason, the first .then() function is being called prior to the full AJAX response, resulting in promise object (response) being <state>: "pending"

Which leads to an unwanted output as I'm not getting the data I wanted to get.

I've looked at multiple documents on I can't seem to find anything on my end that I'm doing incorrectly.

Any ideas?

Eric R
  • 673
  • 2
  • 9
  • 15
  • Are you running this on the website ccchapel.com? If not, you'll need cross-origin support on the server. Check out an answer on [CORS-header ‘Access-Control-Allow-Origin’](http://stackoverflow.com/a/10636765/5459839) – trincot Jan 10 '17 at 21:34
  • 1
    `response` is not a promise object, you must be logging something else. – Bergi Jan 10 '17 at 21:44

2 Answers2

0

The posted code is fine as it is. Replace the url with

var url = 
  "data:application/octet-stream;base64,eyJncmVldGluZyI6ICJoZWxsbyBmb2xrcyJ9Cgo=";

({"greeting": "hello folks"}) to see it in action.

What appears to be missing is a .catch clause on the promise chain to report parsing errors in the .json file.

traktor
  • 17,588
  • 4
  • 32
  • 53
-1

After a bit more Googling, I found this article by Google: https://developers.google.com/web/updates/2015/03/introduction-to-fetch#chaining-promises

Looks like you have to build some extra functions to wait for the status to be resolved. This will then pass the response properly, as you'd expect.

Eric R
  • 673
  • 2
  • 9
  • 15