Question

I need to execute a function on an object as soon as it becomes available. Here is some simplified code of what I'm trying to achieve:

//Display profile should be called as soon as get profile returns its value
displayProfile( getProfile(link) );

var displayProfile = function( obj ){
   console.log('Profile should display');
}

var getProfile = function( link ){
    profiles[ link.attr('profile-name') ] = {
        //Some profile specific info
    }

    //Profile object becomes ready to return after some time 
    setTimeout(function(){
        console.log('Returning profile object');
        return profiles[link.attr('profile-name')];
    }, 400);
}

So the problem is that displayProfile() is executing before the profile object is ready. Could someone suggest how I could execute displayProfile() only once getProfile() has returned a value?

Was it helpful?

Solution

The operation is asyncronous, so you need to use some kind of callback or promise. Here's a basic callback example:

var getProfile = function( link, callback ){
    profiles[ link.attr('profile-name') ] = {
        //Some profile specific info
    }

    //Profile object becomes ready to return after some time 
    setTimeout(function(){
        console.log('Returning profile object');
        callback(profiles[link.attr('profile-name')]);
    }, 400);
}

getProfile(link, function(result){
   displayProfile(result); 
});

The getProfile function now takes a callback as the second argument, which is called when the timer completes, passing the profile name.

OTHER TIPS

You want to have a look at promises or futures. If you are using jQuery, their implementation is based on $.Deferred.

http://microjs.com/#promises

Perhaps this might give you more for the promise:

https://api.jquery.com/promise/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top