2014-09-17 7 views
1

기능 onetwo으로 값을 전달하고 twothree으로 값을 전달합니다. 이 함수들 중 어떤 것도 데이터를 반환하기 위해 어느 정도의 시간이 걸릴 수 있습니다. 앞을 서두르고 undefined을 인쇄하는 대신에 어떻게 가치를 기다리게 할 수 있습니까?AngularJS : Seqential 약속 체인

var deferred = $q.defer(); 

var one = function (msg) { 
    $timeout(function() { 
    console.log(msg); 
    return "pass this to two"; 
    }, 2000); 
}; 

var two = function (msg) { 
    console.log(msg); 
    return "pass this to three"; 
}; 

var three = function (msg) { 
    console.log(msg); 
}; 

deferred.promise 
    .then(one) 
    .then(two) 
    .then(three); 

deferred.resolve("pass this to one"); 

답변

3

당신은 return 뭔가 비동기 않는 모든 함수에서 약속을해야합니다. 당신이 타임 아웃 후 "pass this to two" 값 만든 약속을 반환해야하는 동안 경우

, 당신의 one 기능, undefined 반환하는 대신 var deferred = $q.defer();를 사용하는 BTW,

function one (msg) { 
    return $timeout(function() { 
//^^^^^^ 
    console.log(msg); 
    return "pass this to two"; 
    }, 2000); 
} 

을, 체인이다 더 나은 것으로 작성된 :

one("pass this to one") 
    .then(two) 
    .then(three); 
+0

훌륭한 작품. 감사. –