Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value in a JS asynchronous callback function - gapi

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();
like image 880
Jimmy Avatar asked Nov 09 '19 22:11

Jimmy


People also ask

Can I return value from callback function JavaScript?

A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value. Yes, it makes fun sense to try and return a value from a promise callback.

Which callback function is passed the returned data?

The function to which the callback is passed is often referred to as a higher-order function. Conversely, Higher-Order Functions operate on other functions by either taking them as arguments or by returning them.

What is gapi in JS?

GAPI is Google's client library for browser-side JavaScript. It's used in Google Sign-in, Google Drive, and thousands of internal and external web pages for easily connecting with Google APIs.


2 Answers

Wrap the load in a Promise so that you can await it like the rest of your code.

try {
  await new Promise((resolve,reject) => {
    gapi.load('client:auth2', resolve);
  });
  await authenticate();
  await loadYoutubeApi();
} catch (error) {
  throw Error(`Error initializing gapi client: ${error}`);
}
//is Initialized
like image 160
Klaycon Avatar answered Oct 08 '22 15:10

Klaycon


You can wrap gapi.load part in a promise like this:

const initialize = async () => {
  const { gapi } = window;
  await new Promise((resolve, reject) => {
    gapi.load('client:auth2', async () => {
      try {
        await authenticate();
        await loadYoutubeApi();
        resolve();
      } catch (error) {
        throw Error(`Error initializing gapi client: ${error}`);
      }
    });
  });
  return true;
};

initialize(); // returns 'true' when done.
like image 23
Anton Tuyakhov Avatar answered Oct 08 '22 17:10

Anton Tuyakhov