Javascript each()链接承诺

Javascript each()链接承诺,javascript,parse-platform,promise,parse-cloud-code,Javascript,Parse Platform,Promise,Parse Cloud Code,我正在Parse.comCloudCode上编写一个后台作业函数。作业需要使用不同的参数多次调用同一个函数(包括Parse.Query.each()调用),我想用承诺链接这些调用。以下是我目前掌握的情况: Parse.Cloud.job("threadAutoReminders", function(request, response) { processThreads(parameters1).then(function() { return processThrea

我正在
Parse.com
CloudCode
上编写一个
后台作业
函数。
作业
需要使用不同的参数多次调用同一个函数(包括
Parse.Query.each()
调用),我想用承诺链接这些调用。以下是我目前掌握的情况:

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()中会发生什么情况
    返回零结果?承诺链是否会继续执行?我这么问是因为目前“你好”从未被记录

以下示例显示了使用web浏览器实现的函数内部的使用承诺

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;
}
承诺的实现:

网络浏览器

jQuery

角度$q

我是否正确使用承诺链接函数调用

threadQuery中发生了什么。each()返回零个结果?承诺链是否会继续执行?我这样问是因为目前“你好”从未被记录

我想我说得对,如果“做点什么”是同步的,那么只有在以下情况下才能出现零条“你好”消息:

  • 在记录可能的“Hello”之前,“do something”中出现未捕获错误,或者
  • 每个阶段都没有结果(怀疑您的数据、查询或期望)
你可以通过捕捉错误来免疫自己。由于解析承诺不安全,您需要手动捕获它们:

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

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

是否
each()
返回一个承诺?它的回调做什么?
each()
不返回任何内容,它只是更新一个对象并将其存储在数组中。在
processThreads
中是否有任何异步内容?那么也没有理由使用承诺。只需同步多次调用该函数,而不需要任何
链接,那么
each()函数如何?我会让其中几个同时运行,对吗?(a) 解析后台作业中的并发进程是否没有限制?(b) 多个线程同时写入同一数组可以吗?根据我的代码日志,我看到的问题是,如果没有找到线程,
each()
回调中没有任何内容被调用是的,很可能是这样。通过不使用“doSomething”运行来消除另一种可能性,只需
console.log(“Hello”)