[英]How to return the json response from the fetch API
我有一个这样的功能:
check_auth(){
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
return json.user_logged_in;
});
}
然后我尝试这样做:
if(this.check_auth()){
// do stuff
} else {
// do other stuff
}
但是, this.check_auth()
总是undefined
。
我在这里缺少什么? 我认为在 fetch 的then()
是解析的Promise 对象所在的位置,因此我认为当用户登录时我会得到true
。但事实并非如此。
任何帮助将不胜感激。
使用回调
check_auth(callback){
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
callback(json.user_logged_in);
});
}
check_auth(function(data) {
//processing the data
console.log(d);
});
在 React 中,它应该更容易处理,您可以调用 fetch 并更新状态,因为在每次使用 setState 更新状态时,都会调用渲染方法,您可以使用状态进行渲染
check_auth = () =>{
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
this.setState({Result: json.user_logged_in});
});
}
当您使用.then()
时.then()
异步调用并不总是可以在您的应用程序中的任何地方使用。 呼叫仍然是异步,你需要打电话给你if
语句来当你打电话给你fetch
。 因此,任何依赖于您正在获取的数据的内容都必须使用.then()
链接到fetch
。
check_auth(){
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
return json.user_logged_in;
}).then(user => checkIfAuthSuccess(user)); //You have to chain it
}
将您的if
语句包装在一个函数中,或者您的代码看起来像。
checkIfAuthSuccess(user){
if(user){
// do stuff
} else {
// do other stuff
}
}
关于 JavaScript 中异步行为的精彩视频: Philip Roberts:事件循环到底是什么? | JSConf 欧盟 2014
可以用es6 aync
函数解决
注意:该示例与 OP 所要求的不同,但它提供了一些有关如何完成的提示
const loadPosts = async () => {
const response = await fetch(/* your fetch request */);
const posts = await response.json();
return posts;
};
要从 Promise 以 JSON 形式返回数据,您应该使用async 函数中的await修饰符调用它。
例如:
const checkAuth = async () => {
const data = await fetch(Urls.check_auth())
.then(response => response.json())
.then(json => json.user_logged_in)
return data;
}
您可以在此处找到有关承诺的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.