这是我用来从Parse数据库获取对象总数的函数之一。
var getCount = function() {
var deferred = $q.defer()
var query = new Parse.Query(Parse.Object.extend("MyObj"));
query.count({
success: function(count) {
deferred.resolve(count);
},
error: function(e) {
deferred.reject(e);
}
});
return deferred.promise;
}
我在下面的另一个函数中使用上述函数。
var getRandom = function() {
var deferred = $q.defer()
var Card = Parse.Object.extend("MyObj");
var cardCount;
getCount().then(function(count) {
cardCount = count;
// This call does not update the cardcount value
});
console.log(cardCount); //Always undefined. Not waiting for above call.
query1 = new Parse.Query(Card);
query1.skip(Math.floor(Math.random() * cardCount));
query1.limit(1);
query1 .find({
success: function(results) {
deferred.resolve(results);
},
error: function(e) {
deferred.reject(e);
}
});
return deferred.promise;
}
问题是main函数不等待getCount()函数完成。因此,count变量总是未定义的。
如何制作代码以便在移动到下一行之前完成计数功能并获得值?
答案 0 :(得分:1)
getBlouseCount().then(function(count) {
cardCount = count;
// put the code that needs the cardCount to be known HERE.
});
// NOT here
答案 1 :(得分:0)
这是因为GetCount被推迟了。它将立即返回,然后您使用cardCount而不设置它。
答案 2 :(得分:0)
对于更优雅的解决方案,您可以将count
作为参数
var getRandom = function(count) {
var deferred = $q.defer()
var Card = Parse.Object.extend("MyObj");
var cardCount = count;
query1 = new Parse.Query(Card);
query1.skip(Math.floor(Math.random() * cardCount));
query1.limit(1);
query1 .find({
success: function(results) {
deferred.resolve(results);
},
error: function(e) {
deferred.reject(e);
}
});
return deferred.promise;
}
然后调用getCount.then(getRandom)