未定义指标的阵列异步请求后, [英] Undefined Indexes in Array after Asynchronous Requests

查看:113
本文介绍了未定义指标的阵列异步请求后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组是(异步调用之外)一定的难度非常清楚定义的,但是当我调用它的指标的异步请求的内部(如$ .getJSON)阵列的所有索引是不确定的,但中的长度的仍然是相同的。这是我的code。

I'm having some difficulty with an array that is (outside of an asynchronous call) perfectly well-defined but when I call its indices inside an asynch request (e.g. $.getJSON) all the indices of the array are undefined but the length is still the same. Here is my code.

我这里指的是阵列的 friendsArray

该阵列具有正确的索引在第二个$ .getJSON呼叫,但该函数的回调里面所有的指标是不确定的。如果不是数组保持其价值,因为它是该方法的范围内定义的?

The array has the correct index during the second "$.getJSON" call but inside the callback of that function all its indices become undefined. Shouldn't the array keep its values since it was defined within the scope of the method?

if (response.status === 'connected') { 
var accessToken = $.trim(response.authResponse.accessToken);
var hashArray = [];
var friendArray = [];
document.getElementById("statusCheck").innerHTML = accessToken;
$.getJSON('https://graph.facebook.com/me/friends?access_token=' + accessToken, 
  function(dataJSON){
    hashArray = dataJSON['data'];
    for (var i = 0; i < hashArray.length; i++){
        friendArray.push(hashArray[i]["id"]);
    }
    var resultJSON = "{";
    var resultArray = [];

    for (var i = 0; i < friendArray.length; i++){
        $.getJSON('https://graph.facebook.com/me/mutualfriends/' + 
                  friendArray[i] + "?access_token=" + accessToken, 
            function(dataJSON2){
                resultArray = dataJSON2['data'];
                resultJSON += friendArray[i] + ":" + resultArray.length + ",";
                //alert(resultJSON);
            })
        if (i == friendArray.length - 1){
            postArrayPopulation(resultJSON);
        }
    }

});         

}

推荐答案

问题是,回调函数发生在AJAX功能完成后一段时间后。届时,数组索引已经发展到了你的年底循环(因此它指向离开阵列的末尾)为不确定的值。该阵列仍然存在,但你的指数已被完成函数被调用的时候改变了。

The problem is that the callback function happens some time later when the ajax function completes. By then, the array index has advanced to the end of your for loop (thus it points off the end of the array) to an undefined value. The array is still there, but your index has been changed by the time the completion function is called.

通常用于获取索引的成功处理程序的技术是捕捉到它的函数闭包在那里它被捕获在完成功能的使用。

The technique usually used to get the index into the success handler is to capture it in a function closure where it gets captured for use in the completion function.

您可以创建一个闭包,通过这个替换你的成功处理程序捕获的索引值:

You can create a closure that captures the index value by replacing your success handler with this:

(function(index) {
    return function(dataJSON2) {
        resultArray = dataJSON2['data'];
        resultJSON += friendArray[index] + ":" + resultArray.length + ",";
        //alert(resultJSON);
    }
}) (i);

此外函数执行,并创建一个封闭其捕获i的值和唯一地使得它的成功处理程序可用。当自我执行,它会返回因此被传递到的getJSON功能,你的成功处理程序稍后调用。但是,当它被称为后的值,你需要通过在自执行的函数的参数是提供给成功处理程序。

This outer function executes and creates a closure which captures the value of i and uniquely makes it available to the success handler. When it self executes, it returns your success handler which is thus passed to the getJSON function to be called later. But, when it is called later the value of i that you need is available to the success handler via the argument in the self executing function.

下面是另一种方式来思考与回调使用封闭。

Here's another way to think about closures used with callbacks.

  1. 在任何功能都可以访问所有的范围内,当它声明的变量,即使变量均达到在更高层次上的父范围和即使函数以后作为回调调用。这实际上是JavaScript的一个巨大的特点,许多其他语言都没有。
  2. 所以,如果我们想要一个变量来提供给一个回调函数后回调执行的时候,我们只需要以某种方式获得该变量成回调函数的范围。

下面是一个例子:

function cycleOnOff(sel, cnt, delay) {
    var obj = $(sel);

    function next() {
        if (cnt-- > 0) {
            obj.toggle();
            setTimeout(next, delay);
        }
    }
    next();
}

在这种情况下,该功能下一个()是一个回调的setTimeout(),但功能有完全访问它的父范围内的变量: SEL CNT 延迟 OBJ

In this case, the function next() is a callback to setTimeout(), but that function has full access to the variables within its parent scope: sel, cnt, delay and obj.

  1. 如果变量不回调最初设定的时间,当回调被调用,那么它的pretty的轻松之间切换。你可以只使用一个匿名函数声明以及所有更高范围变量可以在定义匿名函数的时候仍然可以使用,当回调被调用在一段时间后。
  2. 如果变量确实变化code将继续执行,并要进行一个特定的值,它现在已经可以回调时,它后来被称为 - 这是当它变得有点棘手。什么人可以做的是创建你通过这个变量为一个函数,从而创建一个范围,其中的变量有你想要的值,并在那里与其他code继续执行,也不会改变。但是,因为我们要的是一个回调函数,而不是一个函数调用,我们必须将两者结合在一个半奇怪的方式。我们做一个函数调用,并将其传递所需的值。在该函数调用,我们返回一个引用回调函数。此适当地分配回调函数,但它把回调函数成闭合,抓住我们所期望的变量的值。更好的是,本封闭件是唯一的回调的这个特定实例,以便每次使用回调将具有它自己的封闭件和该变量从而它自己的独特的价值。我们为您的特定问题产生的闭合/回调是一个这样的例子。

这篇关于未定义指标的阵列异步请求后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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