简体   繁体   中英

How can I access a value from callback function outside of the callback?

I call a function that takes a callback function parameter.

I want to push the value given to the callback onto a new array so I can use it somewhere else. Problem is that the array stays empty whatever I do.

var testarray = new Array();

Getfirstpictures(id, function(myarray) {
    testarray.push(myarray[0]);
});

alert(testarray);

Since it uses a callback, it is a pretty safe bet that Getfirstpictures is an asynchronous function.

You are calling alert before whatever triggers the callback has happened.

You need to wait until the trigger has occurred (usually by putting the alert inside the callback function.

Use your callback:

    Getfirstpictures(id, function(myarray)
    {
        alert(myarray);
    });

That call back is not executed immediately. It is executed by your Getfirpictures method.


EDIT:

Change:

var testarray = new Array();

Getfirstpictures(id, function(myarray) {
    testarray.push(myarray[0]);
});

alert(testarray);

to:

Getfirstpictures(id, function(myarray) {
     alert(myarray);
});

and it will work. So you can also do something like this:

Getfirstpictures(id, function(myarray) {
     doSomething(myarray);
});

function doSomething(arr) {
    for (var i = 0; i < arr.length; i++)
        alert(arr[i]); // or add elements to the DOM etc etc
}

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