Extract Data from Anonymous Function Scope

2019-07-07 07:08发布

问题:

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;
}

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.

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.

回答1:

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).

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!!!
});

Or:

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

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