我正在尝试创建一个返回承诺的函数,并且在该函数内部,我有一个angular.forEach返回承诺。 这是示例代码:
function func1() {
func2(demoText, demoObject).then(function(response) {
console.log(response);
});
}
function func2(demoText, demoObject) {
var deferred = $q.defer();
var returnString = "someReturnString";
var keepGoing = true;
var loopPromises = [];
angular.forEach(demoObject, function(value, key) {
if(keepGoing) {
var deferred2 = $q.defer();
loopPromises.push(deferred2.promise);
if(value.type == 'other') {
someService.getDataFromServer()
.then(function(serverResponse) {
returnString = serverResponse;
deferred2.resolve();
});
keepGoing = false;
}
else {
deferred2.resolve();
}
}
});
return $q.all(loopPromises).then(function () {
deferred.resolve(returnString);
return deferred.promise;
});
}
现在返回的值是“ someReturnString”,这意味着在我从服务器获取结果之前,已对该值进行了重新调整。
如何解决?