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

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

问题描述

由于该应用程序的复杂性,我需要像这样包装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之后立即使用从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).

否则,您需要了解您正在此处进行 async 呼叫.这意味着您应该将处理代码放在传递给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天全站免登陆