Unexpected end of JSON input on Promise resolve

被刻印的时光 ゝ 提交于 2019-12-23 05:16:43

问题


I am requesting weather data from openweather API and I get "error SyntaxError: Unexpected end of JSON input at Object.parse ()" every time my promise is resolved and I do JSON.pase(daat) The JSON I get looks like this:

{
 "coord":{"lon":24.94,"lat":60.17},
 "weather":[{"id":741,"main":"Fog","description":"fog","icon":"50n"}],
 "base":"stations",
 "main":{"temp":273.15,"pressure":994,"humidity":94,"temp_min":273.15,"temp_max":273.15},
 "visibility":500,
 "wind":{"speed":1.5},
 "clouds":{"all":90},
 "dt":1489872000,
 "sys":{"type":1,"id":5019,"message":0.4444,"country":"FI","sunrise":1489811101,"sunset":1489854738},
 "id":658225,
 "name":"Helsinki",
 "cod":200
}

And it seems to be perfectly valid, at least requesting it from normal JS file. Although from my React app (see issue: ) My code looks like this:

httpRequestWeather(weatherNowHTTPQuery + "Helsinki" + weatherAPIToken).then(function(data){

    let myData = JSON.parse(data);
     //always returns error when trying to do JSON.parse()
    self.setState({
        weatherConditions: "Weather is here!"
     });
    self.setState({
        //always returns error when trying to do JSON.parse()
        weatherObj: JSON.parse(data)
    });

}).catch(function(err){
    console.log("error", err);
    self.setState({
        weatherConditions: "Buy"
     });

However, inside of the http request the data is parsed perfectly fine:

function httpRequestWeather(url) {
    return new Promise(function(resolve, reject) {
        var weatherRequest = new XMLHttpRequest();
        weatherRequest.open("GET", url, true);
        weatherRequest.onreadystatechange = function() {
            if ( this.status === 200) {
                console.log("request finished and response is ready");
                console.log(this.response);
                //this works perfectly fine

                self.setState({
                    weatherConditions: this.response
                 });
                resolve(this.response);
            } else{
                reject(new Error("no weather data"));
            }
          };
        weatherRequest.send();
    });
  }

回答1:


You're not checking the readyState. status can be 200 before readyState is 4. Remember, you get multiple callbacks to the onreadystatechange handler, but a promise can only be resolved once.

So change:

if ( this.status === 200) {
    // ...success...
} else {
    // ...error...
}

to

if ( this.readyState === 4 ) {
    if ( this.status === 200) {
        // ...success...
    } else {
        // ...error...
    }
}

Here's your original on jsFiddle (slightly modified to work with jsFiddle's JSON echo stuff), showing the error: https://jsfiddle.net/2n4to7go/

And here's one with the update above, showing it working: https://jsfiddle.net/2n4to7go/1/



来源:https://stackoverflow.com/questions/42885936/unexpected-end-of-json-input-on-promise-resolve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!