JS异步回调函数中如何return一个值 - gapi

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

我在我的应用程序中使用 google 的 api 客户端。我有一个名为 initialize 的函数,它使用 gapi.load 来验证我的凭据并加载 youtube api。

gapi.load 接受一个回调函数,这是我 authenticateloadYoutubeApi 异步执行的地方。我想知道,当我 运行 的 initialize 函数时,这些异步函数何时完成。有没有办法让我在这个异步回调函数中 return 一个值,这样我就知道,在调用 initialize 时,这些异步任务已经完成?谢谢!

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();

将负载包装在 Promise 中,以便您可以像其他代码一样等待它。

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

您可以将 gapi.load 部分包装在这样的承诺中:

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.