下面是一些代码,部分有效,部分无效。 我尝试(尽可能)仅保留与我的问题相关的部分。 在代码后查看我的担忧。
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)
})
);
}
我处理 Promise 的方式做错了,但我不知道是什么。
我想看到 Trace-One,然后 watchFunction 完成它的工作(这部分实际上工作正常),最后看到 Trace-Two,在执行 response.success 之前。
但是发生的情况是我看到 Trace-One,然后我看到 Trace-Three,然后我可以在日志中看到 watchFunction 已完成其应有的工作。而且我从未见过Trace-2。 正如人们所预料的那样,我收到一条消息,提示未调用成功/错误 那么为什么我没有看到Trace-2并跳转到Trace-3? 我想我没有正确地从某个地方返回 promise 。 希望有人能指出我的错误在哪里。
最佳答案
看起来您希望 watchFunction
执行多个查询,每个查询对应一个可以从 typeArray
派生的类名。但如果这些查询成功,watchFunction
肯定会因索引 typeArray
越界而崩溃。该函数还会删除结果,将它们分配给从未引用的虚拟参数。
生成这几个查询的更简单方法是将每个类名称映射到查询该类的 promise 。 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);
}
云函数应该也调用响应错误,并且可以稍微清理一下...
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");
});
您应该会在日志中看到 Trace-One、Trace-Three、Trace-Two,因为“Trace-Two”日志发生在查询完成后。
关于javascript - 在云代码中使用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016963/