I am using google's api client in my application. I have a function called initialize
that uses gapi.load
to authenticate my credentials and load the youtube api.
gapi.load
takes a callback function which is where I authenticate
and loadYoutubeApi
, asynchronously. I want to know, when I run the initialize
function, when these asynchronous functions have completed. Is there a way for me to return a value in this asynchronous callback function so that I know, when invoking initialize
, that these asynchronous tasks have completed? Thanks!
const apiKey = 'my-api-key';
const clientId = 'my-client-id';
const authenticate = async () => {
const { gapi } = window;
try {
await gapi.auth2.init({ clientId });
console.log('authenticated');
} catch (error) {
throw Error(`Error authenticating gapi client: ${error}`);
}
};
const loadYoutubeApi = async () => {
const { gapi } = window;
gapi.client.setApiKey(apiKey);
try {
await gapi.client.load('https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest');
console.log('youtube api loaded');
} catch (error) {
throw Error(`Error loading youtube gapi client: ${error}`);
}
};
const initialize = async () => {
const { gapi } = window;
const isInitialized = await gapi.load('client:auth2', async () => {
try {
await authenticate();
await loadYoutubeApi();
return true;
} catch (error) {
throw Error(`Error initializing gapi client: ${error}`);
}
});
console.log(isInitialized); // expects `true` but am getting `undefined`
};
initialize();
gapi.load
doesn't return a Promise, so you can't usefully await it. – Silvanaauthenticate
andloadYoutubeApi
methods have completed? – Algologyasync
callback function. Make a promise for the load,await
that in yourinitialize
function. – Ironlike