这是一些部分有效但部分无效的代码。
我尝试(尽可能)仅保留与我的问题相关的部分。
看到我的代码后的担忧。

Parse.Cloud.define
("myCloudFunction", function(request, response)
 {
 var recordTypeArray,className,recordListQuery,resultDictionary;
 recordTypeArray = ["LT1","LT2","LT3","RT1","RT2","RT3"];
 resultDictionary = [];

 console.log("Trace-One");
 watchFunction(recordTypeArray,0,resultDictionary).then
 (function(resRcd) {
  console.log("Trace-Two");
  response.success(resultDictionary);
  });
 console.log("Trace-Three");

 });


function watchFunction(typeArray,typeNumber,resDico)
{
    var className,recordListQuery;
    className = "AA_".concat(typeArray[typeNumber]).concat("_ZZ");
    recordListQuery = new Parse.Query(className);

    return (recordListQuery.find().then
            (function(resRcd) {
             // Here some problemless code.
             if (typeNumber++==typeArray.length) return promise(function(){});
             return watchFunction(typeArray,typeNumber,resDico)
             })
            );
}


关于我处理诺言的方式,我做错了事,但我不知道该怎么办。

我想看到Trace-One,然后watchFunction进行工作(这部分实际上工作正常),最后看到Trace-Two,然后执行response.success。

但是发生的是,我看到“跟踪一”,然后看到“跟踪三”,然后我在日志中看到watchFunction已经按预期完成了工作。而且我再也看不到Trace-2。
正如人们所期望的,我收到一条消息,抱怨没有称成功/错误
那么,为什么我看不到Trace-2,却跳到Trace-3?
我想我没有正确地从某个地方返回一个承诺。
我希望有人指出我的错误所在。

最佳答案

看起来您希望watchFunction执行多个查询,每个查询都可以从typeArray派生出每个类名称。但是,如果这些查询成功,则通过将watchFunction索引超出范围可以确保typeArray崩溃。该函数还会删除结果,并将其分配给从未引用的伪参数。

产生这几个查询的一种更简单的方法是将每个类名映射到查询该类的承诺。 Parse.Promise.when()将运行所有查询,并由包含结果的数组的(var arg)数组满足。 (Parse.Query.or()应该这样做,将结果合并到一个数组中)。

因此,修复watchFunction:

// create a collection of promises to query each class indicated
// by type array, return a promise to run all of the promises
function watchFunction(typeArray) {
    var promises = [];
    for (i=0; i<typeArray.length; ++i) {
        var className = "AA_".concat(typeArray[i]).concat("_ZZ");
        var recordListQuery = new Parse.Query(className);
        promises.push(recordListQuery.find());
    }
    return Parse.Promise.when(promises);
}


cloud函数还应该调用响应错误,并且可以清除一点...

Parse.Cloud.define("myCloudFunction", function(request, response) {

    var recordTypeArray = ["LT1","LT2","LT3","RT1","RT2","RT3"];
    console.log("Trace-One");

    watchFunction(recordTypeArray).then(function() {
       console.log("Trace-Two");
       response.success(arguments);
    }, function(error) {
        console.log("Trace-Two (error)");
        response.error(error);
    });
    console.log("Trace-Three");
});


您应该期望在日志中看到跟踪一,跟踪三,跟踪二,因为“跟踪二”日志在查询完成后发生。

10-06 01:47