2014-04-30 2 views
1

오브젝트가 사용 가능하게 되 자마자 함수를 실행해야합니다. 값이 사용 가능할 때만 함수를 실행하십시오.

//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()이 실행되는 것입니다 : 는 여기에 내가 달성하기 위해 노력하고있어 몇 가지 간단한 코드입니다. 누군가 displayProfile()을 한 번만 실행할 수있는 방법을 제안 할 수 있습니까? getProfile() 값을 반환 했습니까?

답변

0

작업이 asyncronous, 당신은 콜백 또는 약속의 어떤 종류를 사용해야하므로. getProfile 함수는 이제 프로파일 이름을 전달하여 타이머가 완료 될 때 호출되는 제 2 인수로서 콜백을 얻어

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

: 여기서 기본 콜백 예이다.

+0

정확히 내가 필요한 것, 감사합니다 – styke

+0

도움이 되니 기쁩니다. @Downvoter의 의견에 신경 쓰시겠습니까? 비판 환영 :) – MrCode

관련 문제