【问题标题】:Call a function in another javascript function synchronously同步调用另一个javascript函数中的函数
【发布时间】:2016-03-31 15:45:14
【问题描述】:

我试图在getUserAlbum 函数中调用checkLoginStatus 函数,在getUserAlbum 中我正在捕捉checkLoginStatus 的响应返回,并且代表该响应我需要在getUserAlbum 函数下工作。

但问题是这个getUserAlbum 函数不等待响应并执行我不想要的下一行。

这是我的功能:

   var accessToken = '';

   checkLoginStatus = function () {
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                accessToken = response.authResponse.accessToken;
                console.log(accessToken + ' => in check login status');
                return accessToken;
            } else {
                return false;
            }
        });
    }

    getUserAlbum = function () {
        var token = checkLoginStatus();
        console.log(token + ' => in get album function'); // it log undefined here that is why else part executes.
        if(token) {
            FB.api(
                "/me/albums/", {'accessToken': token},
                function (response) {
                  if (response && !response.error) {
                    console.log(response);
                  }
                }
            );
        } else {
            alert("You are not logged in");
        }
    }

有人可以帮我解决这个问题。

【问题讨论】:

  • FB.getLoginStatus 是异步的...使用callbacks
  • 你能告诉我如何使用回调

标签: javascript synchronization


【解决方案1】:

FB.getLoginStatus 是异步的...使用 callbacks 作为 response from FB api 将是异步的。您无法确定何时会收到。

在收到response 之前执行您的函数并返回控制权,因此它将是undefined。

在callbacks 中,您传递function 作为参数将在程序稍后需要时执行。

var accessToken = '';
var checkLoginStatus = function(callback) {
  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
      accessToken = response.authResponse.accessToken;
      callback(accessToken);
    } else {
      callback(false);
    }
  });
}
var getUserAlbum = function() {
  checkLoginStatus(function(token) {
    console.log(token + ' => in get album function'); // it log undefined here that is why else part executes.
    if (token) {
      FB.api(
        "/me/albums/", {
          'accessToken': token
        },
        function(response) {
          if (response && !response.error) {
            console.log(response);
          }
        }
      );
    } else {
      alert("You are not logged in");
    }
  });
}

【讨论】:

  • 非常感谢它有效,现在我明白了问题所在。谢谢你的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2012-02-25
相关资源
最近更新 更多