从匿名函数作用域中提取数据 [英] Extract Data from Anonymous Function Scope

查看:26
本文介绍了从匿名函数作用域中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这个应用程序的复杂性,我需要像这样包装 Facebook API 调用.

Because of the complexity of this application, I have a need to wrap Facebook API calls, like so.

//In main file, read is always undefined
var read = fb_connect.readStream();

// In fb_wrapper.js
function readStream () {
    var stream;

    FB.api('/me/feed', {limit:10000}, function (response) {
        stream = response.data;
    });

    return stream;
}

我知道由于调用的异步性质,readStream() 函数的其余部分将返回 stream(没有值).我无法找到将数据从回调函数作用域中取出并备份到更高作用域的方法.FB API 调用返回正常(我已经调试了一百次),但到目前为止,获取响应数据一直是一场战斗.

I know that due to the asynchronous nature of the call, the rest of the readStream() function will return stream (which has no value). I am having trouble finding a way of getting the data out of the callback function scope and back up to a higher scope. The FB API call is returning fine (I have debugged it a hundred times), but getting that response data has been the battle thus far.

如果有人有任何建议,将不胜感激.我搜索了 Facebook jQuery 插件(可能是预制的包装器),但运气不佳.

If anyone has any suggestions, it would be much appreciated. I searched for Facebook jQuery plug-ins (as a pre-made wrapper, perhaps) with little luck.

推荐答案

从你的问题来看,你好像是在找同步调用.这意味着您希望在调用后立即使用从 api 调用返回的数据.在这种情况下,您需要检查 FB.api 是否支持同步调用(大多数情况下不支持).

Judging from your question, it seems that you are looking for a synchronous call. Which means that you'd want to use the data returned from the api call right after calling it. In that case, you'll need to check whether FB.api supports synchronous calls (mostly doesn't).

否则,您需要了解您正在此处进行异步调用.这意味着您应该将处理代码放在传递给 FB.api 的回调函数中.这称为编写代码的延续"风格,是使用异步调用的标准方式.

Otherwise, you'll need to understand that you are making an async call here. Which means that you should put your handling code INSIDE the callback function that you pass to FB.api. This is called the "continuation" style of writing code and is the standard way to use async calls.

FB.api('/me/feed', {limit:10000}, function (response) {
    var stream = response.data;
    // Do your processing here, not outside!!!
});

或者:

function handlerFunction(response) {
   // Do your processing here
}

FB.api('/me/feed', {limit:10000}, handlerFunction);

这篇关于从匿名函数作用域中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆