三天以来,我一直在尝试使用fetch API来获取JSON对象,我搜索了几乎所有我能找到的线程。所以我有一个使用fetch的函数,我希望这个函数返回一个JSON对象,但当我试图打印它时,它是一个Promise对象。我发现fetch实际上是在返回Promise对象。那么,如果fetch不可能返回JSON对象,我如何从Promise对象获取JSON对象呢?_ParseJSON中的console.info正确地打印出我想要的JSONObject,但是在fetch之外,不可能重新构造JSON。
import React from 'react';
export class JSONObject {
constructor(_url) {
this.URL = _url;
this.importedJSON = null;
this.state = {}; //Init getter setter
}
ParseCurrentUrl() {
this.importedJSON = this._ParseJSON();
console.info(this.importedJSON);
}
_ParseJSON() {
return fetch(this.URL)
.then(response => response.json())
.then((responseJSON) => {
const { statusCode, data } = responseJSON;
console.info("_PARSE");
console.info(responseJSON);
return responseJSON;
})
.catch((e) => {
console.error(e);
})
}
set URL(_newUrl) { this.constructor.URL = _newUrl; }
get URL() { return this.constructor.URL; }
}
发布于 2018-06-10 03:33:29
你说过了
在_ParseJSON中 console.info正确地打印出我想要的JSONObject,但是在获取之外,不可能重新构造JSON
这是因为您不能在promise中返回值。
教训是异步函数不返回(或至少不可靠地返回)
如果您希望在异步函数之后发生某些事情,则需要在异步函数内调用它
您可以使用
_ParseJSON() {
return fetch(this.URL)
.then(response => response.json())
.then((responseJSON) => {
const { status, data } = responseJSON;
console.info("_PARSE");
console.info(responseJSON);
// set the value you want as an example
this.importedJSON = responseJSON;
})
.catch((e) => {
console.error(e);
})
}
相反,
希望这能对你有所帮助。
https://stackoverflow.com/questions/50777686
复制相似问题