如何将Google API客户端库用于JavaScript(GAPI)与异步/等待?
我有一个使用(也称为GAPI)。
所有官方代码示例都使用了复杂的回调混乱。相反,我想使用异步/等待它实现它。
I found
根据教程,我将其放在我的< head>
我的 index.template.html
:
<!DOCTYPE html>
<html>
<head>
<script
async
defer
src="https://apis.google.com/js/api.js"
onload="window.gapiLoaded()"
onerror="window.gapiLoadError(event)"
></script>
</head>
<body>
<div id="q-app"></div>
</body>
</html>
然后,我将教程的其他部分组合到我自己的 load> load> load> load> load> load>
函数。它放置在VUE组合中,并在单个文件组件(SFC)中调用:
export const loadGooglePeopleApi = async (accessToken: string) => {
// Wait for the defered gapi script tag to finish loading
await new Promise((res, rej) => {
window.gapiLoaded = res;
window.gapiLoadError = rej;
});
// Load Google API Client Library (aka gapi)
await new Promise((res, rej) => {
gapi.load('client', { callback: res, onerror: rej });
});
// Load an interface for the Google People API
await gapi.client.load('https://people.googleapis.com/$discovery/rest');
// Set the access_token
gapi.client.setToken({ access_token: accessToken });
};
不幸的是,它会产生某些打字稿错误,因为这些类型在> window
>:
Property 'gapiLoaded' does not exist on type 'Window & typeof globalThis'. ts(2339)
Property 'gapiLoadError' does not exist on type 'Window & typeof globalThis'. ts(2339)
所以我添加了类似的类型:
declare global {
interface Window {
gapiLoaded?: (value: unknown) => void;
gapiLoadError?: (reason?: any) => void;
}
}
但是现在,每当页面加载时,我都会在控制台中遇到此错误:
Uncaught TypeError: window.gapiLoaded is not a function
我是否正确实现了此错误?为什么我会出现控制台错误?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论