简体   繁体   中英

How to update and pass a variable in a call back function

I am using SoundCloud API, and I made a function with a callback that first it gets a song URL, then by SoundCloud API it gets the sound ID related to that URL then pass that ID to the callback to use it for streaming and updating the page. It does gather the data from API but the varibale get updated locally and in public it stays UNDEFINED.

Here is the code and DEMO : http://jsfiddle.net/aq309twd/

function transfer(item, callback) {

    permalink_url = myURL;

    SC.get('http://api.soundcloud.com/resolve.json?url=' + permalink_url + '/tracks&client_id=' + client_id, function (result) {
        trackID = result.id;
    });

    callback(trackID);
}
transfer("", function (num) {
    //$(".item").text(num);
    SC.get("/tracks/" + num, function (sound) {
        SC.stream("/tracks/" + num, function (sound) {
            //somefountion
        });

    });

});

At SC.get the trackID gets updated, but anywhere outside this function its undefined. Any idea?

Thanks in advance.

Your function SC.get looks like it is performing an async operation probably an Ajax call therefore what is executed on the next line callback(trackID); it is not executed at the same time the ajax call is responding.

It would make more sense to move your callback function inside the SC.get like:

SC.get('http://api.soundcloud.com/resolve.json?url=' + permalink_url + '/tracks&client_id=' + client_id, function (result) {
    var trackID = result.id;
    callback(trackID);
});

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