将API调用电子邮件存储在变量中



我在将用户的电子邮件地址存储在JavaScript中的变量中遇到了麻烦。我想做的是调用API,获取电子邮件地址,然后将其存储在"电子邮件"变量中,以在屏幕上使用其他功能。

我的代码看起来像这样:

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

我确实检查了以确保我拥有适当的权限。我会将alert(response.email)放在我的响应部分中,并通过适当的电子邮件提醒。问题是我无法获得函数的电子邮件变量

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

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

另一种方式是使用承诺,期货或递延(确实是同一件事)来抽象这一点。

最新更新