【发布时间】:2017-11-19 04:54:53
【问题描述】:
我以为我已经解决了这个 Promises 问题,但是无论 1000 项限制如何,这个从 Query 中获取所有结果的功能都无法正常工作。任何人都可以向我解释我要去哪里错了吗?谢谢!
此 Cloud Job 在我的 main.js 文件中:
//in main.js
Parse.Cloud.job("testQuery", function(request, status) {
var theClass = Parse.Object.extend("SomeClass");
var theQuery = new Parse.Query(theClass);
console.log("Here we go...");
queryHelper.getAllResultsForQuery(theQuery, console).then( function(result) {
//This code is called before getAllResultsForQuery finishes
console.log("Finished the search!");
status.success("yay");
}, function(error) {
console.log("Fail " + error);
status.error("failed!");
});
});
而且这个函数在queryHelper.js中:
//in queryHelper.js
exports.getAllResultsForQuery = function(query, console) {
var resultArray = [];
var limit = 1000;
var sendQuery = function(skip) {
if (skip) {
query.greaterThan("createdAt", skip);
}
query.limit(limit);
query.ascending("createdAt");
query.find().then(function (newResults) {
receivedResults(newResults);
}, function (error) {
return Parse.Promise.error(new Error("query failed after " + resultArray.length + " results, error:" + error));
});
};
var receivedResults = function(received) {
resultArray = resultArray.concat(received);
console.log("Got " + received.length + " objects, now at " + resultArray.length);
if (received.length == limit) {
sendQuery(received[received.length-1].createdAt);
} else {
console.log("returning from getAllResults...");
return resultArray;
}
};
sendQuery();
};
当我运行代码时,queryHelper.getAllResultsForQuery 函数似乎运行得很好,但 Promise 似乎在该函数完成之前触发,因此控制台输出如下所示:
"Here we go…";
"Finished the search!";
"Got 1000 objects, now at 1000";
"Got 1000 objects, now at 2000";
"Got 1000 objects, now at 3000";
"Got 245 objects, now at 3245";
"returning from getAllResults…";
我是不是在某个地方犯了新手错误?
【问题讨论】:
标签: javascript parse-platform promise parse-cloud-code