【问题标题】:How to return a value in a JS asynchronous callback function - gapi如何在 JS 异步回调函数中返回一个值 - gapi
【发布时间】:2020-03-06 02:51:59
【问题描述】:

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

gapi.load 采用一个回调函数,这是我 authenticateloadYoutubeApi 异步的地方。我想知道,当我运行initialize 函数时,这些异步函数何时完成。有没有办法让我在这个异步回调函数中返回一个值,以便在调用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();

【问题讨论】:

  • gapi.load 不返回 Promise,因此您无法有效地等待它。
  • 是的,我真的不这么认为。如何深入了解 authenticateloadYoutubeApi 方法何时完成?
  • How do I convert an existing callback API to promises? 的可能重复项。不要传递async 回调函数。在你的 initialize 函数中为负载做出承诺,await that

标签: javascript google-api async-await google-api-js-client


【解决方案1】:

将负载包装在 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

【讨论】:

    【解决方案2】:

    您可以将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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-14
      相关资源
      最近更新 更多