Javascript 仅当值可用时才执行函数

Javascript 仅当值可用时才执行函数,javascript,return,Javascript,Return,我需要在对象可用时立即对其执行函数。 以下是我试图实现的一些简化代码: //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 = f

我需要在对象可用时立即对其执行函数。 以下是我试图实现的一些简化代码:

//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);
}

所以问题是displayProfile是在profile对象准备就绪之前执行的。有人能建议我如何仅在getProfile返回值后执行displayProfile吗

你想看看承诺或未来。如果您使用的是jQuery,则它们的实现基于$.Deferred


也许这会给你更多的承诺:


该操作是异步的,因此需要使用某种回调或承诺。下面是一个基本的回调示例:

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); 
});

getProfile函数现在将回调作为第二个参数,在计时器完成时调用该参数,并传递配置文件名。

很高兴它有所帮助@有什么评论吗?欢迎批评: