问题描述
我试图检查一个用户是否登录,但是我得到的结果很不一致,似乎涉及到某种竞争条件。我基本上使用了的代码:
I'm trying to check if a user is signed in or not, but I'm getting really inconsistent results that seem to have some sort of race condition involved. I basically took the code Google Developer Website:
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'my_client_id.apps.googleusercontent.com',
});
console.log(auth2.isSignedIn.get());
setTimeout(function(){console.log(auth2.isSignedIn.get())},50);
setTimeout(function(){console.log(auth2.isSignedIn.get())},500);
setTimeout(function(){console.log(auth2.isSignedIn.get())},1000);
});
由于某些原因,前两个返回false,第二个返回true。我有双重检查,并且我登录,所以看起来前两个应该返回true。我在想她吗?我查看了文档,似乎没有任何表明异步发生的东西,我不确定我应该等待什么,然后才能从获得可靠的结果。 isSignedIn
call。
For some reason, the first two return false, and the second to return true. I have double checked, and I am signed in, so it seems like the first two should be returning true. What am I missing her? I've looked at the documentation, and there doesn't seem to be anything that indicated something asynchronous happening, and I'm not sure what I should be waiting on before I can get a reliable result from the isSignedIn
call.
推荐答案
也许我在文档的某个地方错过了它(如果我这样做了,如果有人能指出我的意思,d就很好),但看起来你可以使用Promise来确保GoogleAuth实例已经准备就绪。这是我做了一个一致的结果:
Maybe I missed it in the documentation somewhere (if I did, it'd be nice if someone could point it out to me), but it looks like you can use Promises to make sure the GoogleAuth instance is ready. Here's what I did to get a consistent result:
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'my_client_info.apps.googleusercontent.com',
}).then(function(){
auth2 = gapi.auth2.getAuthInstance();
console.log(auth2.isSignedIn.get()); //now this always returns correctly
});
});
这篇关于Google Sign In API:isSignedIn.get()返回不一致的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!