Parse.Query.each()链接承诺

时间:2015-11-10 16:45:28

标签: javascript parse-platform promise cloud-code

我在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
    });
}

我的问题是:

  • 我是否正确使用promises链接函数调用?
  • threadQuery.each()中发生的事情会返回零结果?承诺链会继续执行吗?我问,因为目前“Hello”永远不会被记录..

2 个答案:

答案 0 :(得分:2)

  

我是否正确使用promises链接函数调用?

  

threadQuery.each()中发生的事情会返回零结果?承诺链会继续执行吗?我问,因为目前“Hello”永远不会被记录。

我认为我说得对,如果“做某事”是同步的,那么零“Hello”消息只会在以下情况下发生:

  • 在记录可能的“Hello”或
  • 之前,在“do something”中发生未被捕获的错误
  • 每个阶段都没有结果(怀疑您的数据,您的查询或您的期望)。

您可以通过捕获它们来免受未捕获错误的影响。由于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

相关问题