我在角度中使用了一系列承诺,我希望在链的末尾应该返回一个值:
this.calculateeventsattended = function(username) {
var Attendees = Parse.Object.extend("Attendees");
var User = Parse.Object.extend("User");
var count_pres = 0
query1 = new Parse.Query(Attendees);
query1.equalTo("user_id",username);
query1.equalTo("presence",true)
var promise = query1.count(function(count){
count_pres = count
}).then(function(){
query2 = new Parse.Query(User);
query2.equalTo("username",username);
query2.first().then(function(object){
alert("parse" + count_pres)
object.set("events_attended",count_pres)
object.save()
})
})
$q.all(promise)
return count_pres
}
链条承诺'在传递返回之前未解析:在$ q.all(promise)完成之前返回count_pres。有什么想法吗?
答案 0 :(得分:1)
我无法想象这会有用吗?这就是你如何链接承诺与如何编写异步承诺。
function chainedPromises() {
return $q(function(resolve) {
query
.firstPromise()
.then(function(firstResult) {
return query.secondPromise(firstResult.something);
})
.then(function(secondResult) {
return query.thirdPromise(secondResult.something);
})
.then(function(thirdResult) {
return query.fourthPromise(thirdResult.something);
})
.then(function(fourthResult) {
resolve(fourthResult);
});
});
}
function asyncPromises() {
var promises = [];
promises.push(query.firstPromise());
promises.push(query.secondPromise());
promises.push(query.thirdPromise());
promises.push(query.fourthPromise());
return $q.all(promises);
}
chainedPromises()
.then(function(fourthResult) {
doSomethingWith(fourthResult);
});
asyncPromises()
.then(function(results) {
doSomethingWith(results);
});