Promise解析时JSON输入的意外结束 [英] Unexpected end of JSON input on Promise resolve

查看:1034
本文介绍了Promise解析时JSON输入的意外结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从openweather API请求天气数据,我得到错误SyntaxError:Object.parse()的JSON输入的意外结束每次我的承诺得到解决并且我做JSON.pase(daat)
JSON我看起来像这样:

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
}

它似乎完全有效,至少从普通的JS文件中请求它。
虽然来自我的React应用程序(请参阅问题:)
我的代码如下所示:

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"
     });

然而,在http请求中,数据被完全解析:

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();
    });
  }


推荐答案

你没有检查 readyState的状态可以 200 之前 readyState 是4.记住,你得到多个回调到 onreadystatechange 处理程序,但是一个承诺只能解决一次。

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.

所以更改:

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

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

这是你在jsFiddle上的原创(稍加修改以适应jsFiddle的JSON echo stuff),显示错误: https://jsfiddle.net/2n4to7go/

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

这里有一个上面的更新,显示它正常工作: https://jsfiddle.net/2n4to7go/1/

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

这篇关于Promise解析时JSON输入的意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆