简体   繁体   English

如何在异步函数中使用数组值

[英]How to use array values in asynchronous function

I have an array, whose values I want to use as input to an asynchronous function. 我有一个数组,我想将其值用作异步函数的输入。 But when I iterate through my array and send them to the asynchronous function, all calls to the asynchronous function seems to be done by the last value in the array. 但是,当我遍历数组并将其发送给异步函数时,对异步函数的所有调用似乎都是由数组中的最后一个值完成的。

I thought that this kind of problems were solved by callbacks, but the function is a library that I'm using, which doesn't provide any callback.. What should I do to make the asynchronous function treat all individual array values?? 我以为此类问题已通过回调解决,但是该函数是我正在使用的库,它不提供任何回调。我应该怎么做才能使异步函数处理所有单个数组值?

var libraryName = new Library("#div");

$.post("myfile.php", {somedata}, function(data){
    console.log(data); //prints all correct values
    for(i in data){
        libraryName.asynchronousFunction({
            name: data[i].name // <--this value only becomes the last value in the data-array for all calls
        });
    }
});

Try something like this because of closures: 由于闭包,尝试这样的事情:

$.post("myfile.php", {somedata}, function(data){
    console.log(data); //prints all correct values
    for(i in data){
        (function(elem) {
            libraryName.asynchronousFunction(
                {name: elem.name}
            );
        })(data[i]);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM