Parse.Query.each()链接承诺

Parse.Query.each() chained promises

本文关键字:链接 承诺 Query each Parse      更新时间:2023-09-26

我正在Parse.com CloudCode上编写一个background job函数。job需要用不同的参数多次调用同一个函数(包括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链接函数调用?

是的。

threadQuery.ech()返回零结果时会发生什么情况?承诺链会继续执行吗?我这么问是因为目前"你好"从未被记录。

我认为我说得对,如果"做某事"是同步的,那么零个"你好"消息只能在以下情况下发生:

  • 在记录潜在的"Hello"之前,"do something"中发生了未捕获的错误,或者
  • 每个阶段都没有给出结果(怀疑您的数据、查询或期望)

你可以通过捕捉未捕获的错误来免疫自己。由于Parse承诺不安全,您需要手动捕获它们:

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

这应该确保迭代继续进行,并返回已实现的承诺。

以下示例显示为使用web浏览器实现的函数内部的use promise。

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;
}

承诺的实现:

Web浏览器https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

jQueryhttps://api.jquery.com/promise/

Angularhttps://docs.angularjs.org/api/ng/service/$q