我正在 Parse.com
CloudCode
上编写一个后台作业
函数。该作业需要使用不同的参数多次调用相同的函数(包括 Parse.Query.each() 调用),并且我想将这些调用与 Promise 链接起来。这是我到目前为止所拥有的:
Parse.Cloud.job("threadAutoReminders", function(request, response) {
processThreads(parameters1).then(function() {
return processThreads(parameters2);
}).then(function() {
return processThreads(parameters3);
}).then(function() {
return processThreads(parameters4);
}).then(function() {
response.success("Success");
}, function(error) {
response.error(JSON.stringify(error));
});
});
下面是processThreads()
函数:
function processThreads(parameters) {
var threadQuery = new Parse.Query("Thread");
threadQuery... // set up query using parameters
return threadQuery.each(function(thread) {
console.log("Hello");
// do something
});
}
我的问题是:
- 我是否正确使用 Promise 来链接函数调用?
threadQuery.each()
返回零结果时会发生什么情况? promise 链会继续执行吗?我这么问是因为目前“Hello”永远不会被记录..
最佳答案
Am I chaining function calls using promises correctly?
是的。
What happens in threadQuery.each() returns zero results? Will the promise chain continue with execution? I'm asking because at the moment "Hello" never gets logged.
我认为我的说法是正确的,如果“做某事”是同步的,那么只有在以下情况下才会发生零“Hello”消息:
- 在记录可能的“Hello”之前,“做某事”中发生 Uncaught Error ,或者
- 每个阶段都不会给出任何结果(怀疑您的数据、查询或期望)。
您可以通过捕获 Uncaught Error 来免疫它们。由于 Parse Promise 不是抛出安全的,因此您需要手动捕获它们:
function processThreads(parameters) {
var threadQuery = new Parse.Query("Thread");
threadQuery... // set up query using parameters
return threadQuery.each(function(thread) {
console.log("Hello");
try {
doSomething(); // synchronous
} catch(e) {
//do nothing
}
});
}
这应该确保迭代继续并返回已履行的 promise 。
关于javascript - Parse.Query.each() 链式 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635151/