Google 人 API Javascript - 将 GivenName 存储为变量

Google People API Javascript - Store GivenName as Variable

我 运行 遇到将 Google API 调用存储为变量的问题。我相信这与变量在 promise 函数中被调用有关,据我所知,它一旦执行就不会传递给全局变量。当前代码的结果是'null',也就是变量的初始值

我删除了大部分代码以显示必要的摘录:

var MyApp {
   name: null
};

function makeApiCall() {
     gapi.client.people.people.get({
       'resourceName': 'people/me',
       'requestMask.includeField': 'person.names'
     }).then(
       function(resp) {
       MyApp.name = resp.result.names[0].givenName;
       return MyApp.name;
     });
}

function getIP(json) {
    makeApiCall();          
    var person = MyApp.name;
    document.write(person);
}

基本上,我希望 MyApp.name(在脚本前面创建的全局变量)的值从 'null' 更改为 API 响应,以便打印的值getIP(json) 是 givenName 而不是 null,这是我当前的输出。

换句话说,当我在 getIP(json) 函数中引用 MyApp.name 时,它应该引用 'resp.result.names[0].givenName' 而不是 'null'.

我已经搜索了一段时间这个主题,但除了知道什么不起作用之外没有任何成功。

通过这样做:

makeApiCall();          
var person = MyApp.name;
document.write(person);

您告诉 Javascript 将 Google API 调用加入队列,然后在等待请求完成之前立即使用结果。

此外,您不应使用 document.write,因为它会用您的变量内容替换整个文档,因为它会在文档呈现后调用。

试试这个:

gapi.client.people.people.get({
  'resourceName': 'people/me',
   'requestMask.includeField': 'person.names'
}).then(
  function(resp) {
    MyApp.name = resp.result.names[0].givenName;
    //Use MyApp.name here and don't use document.write
  });