【问题标题】:Storing an API Call email in a variable将 API 调用电子邮件存储在变量中
【发布时间】:2012-12-08 13:18:55
【问题描述】:

我无法将用户的电子邮件地址存储在 javascript 的变量中。我要做的是调用 API,获取电子邮件地址,并将其存储在“电子邮件”变量中,以用于屏幕上的其他功能。

我的代码如下所示:

function emailCheck(){
    var email;
    FB.api('/me',email = function(response){
        return response.email;
        })
    }

    alert(email);

我确实检查以确保我拥有适当的权限。我会将alert(response.email) 放在我的回复部分,它会通过正确的电子邮件发出警报。问题是我无法在函数外部访问电子邮件变量。

【问题讨论】:

    标签: facebook-graph-api scope user-permissions


    【解决方案1】:

    您需要使用延续,因为所有 API 方法都是异步的

    function emailCheck(continuation){
      FB.api('/me', function(response){
        continuation(response && response.email);
      });
    }
    
    emailCheck(function(email) {
      alert(email);
    }
    

    另一种方法是使用 Promises、Futures 或 deferreds(实际上是一样的)来抽象其中的一部分。

    【讨论】:

    • 啊,异步部分很好。自从我使用 JS SDK 构建以来已经有一段时间了。删除了我的答案并认可了这个。
    • 好的,我似乎无法让它工作。我会使用email = emailcheck(function(email){alert(email);},但我仍然得到'未定义'
    • @RickeyESmith - 异步方法不能返回数据 - 它们必须像我在示例中显示的那样进行回调,继续。
    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多