我有这样的功能:
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
。但事实并非如此
非常感谢任何帮助。
答案 0 :(得分:2)
使用回调
new
在React中它应该更容易处理,你可以调用一个fetch并更新状态,因为在每次使用setState更新状态时都会调用render方法你可以使用状态来渲染
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);
});
答案 1 :(得分:2)
当您使用.then()
时,异步调用并不总是在您应用内的任何位置使用。呼叫仍然是异步的,您需要在致电if
时拨打fetch
- 语句。因此,任何依赖于您提取的数据的内容都必须与fetch
链接到.then()
。
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: What the heck is the event loop anyway? | JSConf EU 2014
答案 2 :(得分:1)
可以使用es6 aync
函数来解决
注意:该示例与OP要求的有所不同,但它提示了应如何操作
const loadPosts = async () => {
const response = await fetch(/* your fetch request */);
const posts = await response.json();
return posts;
};
答案 3 :(得分:0)
要从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;
}
有关您可以找到here的承诺的更多信息