我在background job
Parse.com
上写了一个CloudCode
函数。 job
需要使用不同的参数多次调用相同的函数(包括Parse.Query.each()
调用),并且我希望使用promises链接这些调用。这是我到目前为止所做的:
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
});
}
我的问题是:
threadQuery.each()
中发生的事情会返回零结果?承诺链会继续执行吗?我问,因为目前“Hello”永远不会被记录.. 答案 0 :(得分:2)
我是否正确使用promises链接函数调用?
是
threadQuery.each()中发生的事情会返回零结果?承诺链会继续执行吗?我问,因为目前“Hello”永远不会被记录。
我认为我说得对,如果“做某事”是同步的,那么零“Hello”消息只会在以下情况下发生:
您可以通过捕获它们来免受未捕获错误的影响。由于Parse promise不是throw-safe,你需要手动捕获它们:
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
}
});
}
这应该确保迭代继续并且返回一个履行的承诺。
答案 1 :(得分:1)
以下示例显示使用Web浏览器实现在函数内使用promises。
function processThreads(parameters) {
var promise = new Promise();
var threadQuery = new Parse.Query("Thread");
threadQuery... // set up query using parameters
try {
threadQuery.each(function(thread) {
console.log("Hello");
if (condition) {
throw "Something was wrong with the thread with id " + thread.id;
}
});
} catch (e) {
promise.reject(e);
return promise;
}
promise.resolve();
return promise;
}
承诺的实现:
网络浏览器https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
jQuery https://api.jquery.com/promise/
Angular https://docs.angularjs.org/api/ng/service/ $ q