简体   繁体   中英

Calling an Async function multiple times

I have an Async function

function AsyncFunc(args){
    //does some async work here
}

then I call this function multiple times in a for loop:

for(var i=0; i<10; i++)
{
    AsyncFunc(i);
}

Does this create multiple copies of the AsyncFunc ? or are the local variables defined in AsyncFunc getting overridden by the subsequent calls?

EDIT

Suppose the AsyncFunc does following:

function AsyncFunc(args){
    $.get(args.url, function(data){
        args.data = data;
    });
}

then I call this function multiple times in a for loop:

for(var i=0; i<10; i++)
{
    AsyncFunc(args_object_with_a_different_url);
}

Now would data go into their corresponding args object? In other words, would the callback attach to the copy of the function in which the ajax request was initiated?

The AsynFunc() is placed on the call stack 10 times. Each call contains a localized copy of all variables and functions defined within it. Therefore, they do not share state and "get overriden".

The calls share no state with one another other than any references to objects within the global name space.

EDIT:

Example where they would potentially "share":

var mySharedVariable = 0;

function AsyncFunc(args) {
    var myLocalVariable = mySharedVariable++;
    console.log(myLocalVariable);
   // do some asynchronous task that i'm too lazy to code for the example as it's not relevant
}

for(var i = 0; i < 10; i++)
    AsyncFunc(i);

console.log(mySharedVariable);

As you can see here, if we were to output mySharedVariable at the end, it would output 10. However, if we output myLocalVariable we would see something akin to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 since they are local variables and do not share state.

Edit:

jQuery async call example:

for (var i = 0; i < 10; i++)
     $.post('someURL', function(response) {
         var myLocalVariable = response.data;
         //the data returned is not a copy, it's an individual instance per call invoked.
         //neither is myLocalVariable shared, each invocation of this callback has it's own memory allocated to store its value
     });

Edit: To your most recent question, every data object would be unique to each callback after the get request. However, your code doesn't assure me that the args variable being passed in is different each time so there is a chance that your implementation could lead to args.data being overriden with each callback. So take a look below at another option to ensure you store all of the data objects from your callbacks appropriately.

var args = [];
function AsyncFunc(args){
    $.get(args.url, function(data){
        args.push(data);
    });
}
//now args will have 10 uniquely different data objects stored inside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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