I am using Google Identity Services to setup login for my webpage. I am doing API calls in a async function which returns a Promise resolve but the .then function is executed even before the Promise is resolved. I am temporarily managing it with setTimeout but it isnt a good approach right so please help me out in finding the
const connectOAuth = async () => {
/* global google */
await google.accounts.id.initialize({
client_id: "133396583135-1rar9q7nq2fotg5h6qk085i97s37hi5u.apps.googleusercontent.com",
callback: handleCallBackResponse
})
await google.accounts.id.renderButton(document.getElementById("loginButton"), {theme: "outline", size: "large"})
await google.accounts.id.prompt()
return Promise.resolve()
}
useEffect(() => {
connectOAuth().then(setTimeout(() => {setLoading(false)}, 1000))
}, [])
error
The loading screen should turn off once API calls are done but it goes off before hand spoiling entire css of my webpage
2
Answers
The posted code is calling
setTimeout
when evaluating the argument passed tothen
:executes
(which starts the timeout) before calling
then
.Now because
async
functions return a pending promise when they process anawait
keyword, thethen
method is called on the promise returned whenis called, but before
initialize
has performed any asynchronous work.The solution is to register a promise listener, using
then
, without calling the listener in the process. E.G.Note that returning
promise.resolve()
from an async function is superfluous – falling out the bottom of anasync
function returnsundefined
which will be used to fulfill the promise returned from calling the async function.The issue is with your
.then()
part of the promise chain. The syntax is wrong. The correct syntax for handling promises is:So to fix your code, you need to adjust your code like below:
But if you wish to write a better code, I would recommend you use states for handling all your responses.
Solution for handling responses using states