나는 JavaScript 프로그래밍을 처음 사용하기 때문에 비동기 문제로 정말 고심하고있다. 내가 아래에있는 내 예를 보여주기 위해 노력했다 :각도 - 다중 약속 및 반복 - 결과를 얻는 방법
컨트롤러를
$scope.handleClick = function(stuff) {
var promise = fetchOtherStuffs(stuff.id1);
var promiseTwo = fetchOtherStuffs(stuff.id2);
$q.all([promise, promiseTwo]).then(function(data) {
// fails because data is undefined
console.log(data[0].length);
console.log(data[1].length);
});
};
var fetchOtherStuffs = function(stuffId) {
return $http.get('http://localhost/myapi/stuff/' + stuffId)
.then(function(theStuffs) {
var promises = [];
for (var i = 0; i < theStuffs.data.length; i++) {
var otherStuffId = theStuffs.data[i].otherStuffId;
promises.push(
$http.get('http://localhost:8085/myapi/otherstuff/'
+ otherStuffId));
}
$q.all(promises).then(function(data){
var result = [];
for (var i = 0; i < promises.length; i++) {
result.push(data[i].data[i]);
}
// this works and the data count is as expected
console.log('returning: ' + result.length);
return result;
});
});
};
그래서 내가 필요 :
myapi/stuff
가 호출의 결과를 가지고
- 전화 (여러 될 수있는 객체)를 호출하고 각각의 객체에 대해
/myapi/otherstuff
을 호출하십시오. - otherstuff 다시 handleClick 방법
에 정말 약속은 그것이 handleClick 방법으로 필요한 때 값을 반환 실제로 수익을 오도록 fetchOtherStuffs에게 메소드를 구현하는 방법을 모르겠어요.
고마워요.
return $ q.all (promise) .then (function() {...})'이어야합니다. – dfsq