在循环中解析云代码查询

时间:2015-04-02 12:22:56

标签: javascript parse-platform promise underscore.js cloud-code

我正在尝试制作一个Parse云代码函数来检索“分数”,但它的级别和所有者(如果存在)会更新并创建它。 我不能让它在循环中工作,在更新或插入的分数列表上重复此操作。

以下是我改编自https://parse.com/docs/js_guide#promises-chaining的代码,可以重现我的问题。

我的resultMessage输出:

  

{“result”:“loop loop”}

而不是

  

{“result”:“loop set 100 find set 200 success find loopset 100   找到200集成功“}

Parse.Cloud.define("example2", function(request, response) {
	var resultMessage = ""
	var query = new Parse.Query("ScoreTest");
	var test = ["1", "2"]; // Dumb list to loop over.
	var promise = Parse.Promise.as();
	promise = promise.then(function() { 
		_.each(test, function(elt) {
			resultMessage = resultMessage + " loop ";
			query.find().then(function(students) {
				resultMessage = resultMessage + " set 100 ";
			  students[0].set("score", 100);
			  return students[0].save();
			 
			}).then(function(valedictorian) {
				resultMessage = resultMessage + " find ";
			  return query.find();
			 
			}).then(function(students) {
				resultMessage = resultMessage + " set 200 ";
			  students[0].set("salutatorian", 200);
			  return students[0].save();
			 
			}).then(function(salutatorian) {
					resultMessage = resultMessage + " success ";
					return Parse.Promise.as();
				 
			});
		});
	}).then(function() {
		response.success(resultMessage);
	})
	
});

1 个答案:

答案 0 :(得分:0)

也许我被发布的代码误入歧途。让我们说问题就是这样:通过一些标准检索一个对象。如果存在,请修改并保存。如果它不存在,请创建它。在循环中做所有这些。

让我们为每个逻辑位执行小的,承诺返回的函数:

// return a promise for a Score matching level and owner.  return
// undefined if one doesn't exist
function scoreWithOwnerLevel(owner, level) {
    var query = new Parse.Query("Score");
    query.equalTo("owner", owner);
    query.equalTo("level", level);
    return query.first();
}

// return a promise for either an existing score or a new one matching
// level and owner criteria.  set its otherValue
function findOrCreateScore(owner, level, otherValue) {
    return scoreWithOwnerLevel(owner, level).then(function(score) {
        if (!score) {
            var Score = Parse.Object.extend("Score");
            score = new Score();
            score.set("owner", owner);
            score.set("level", level);
        }
        score.set("otherValue", param.otherValue);
        return score;
    });
}

// take a list of owners, levels and one other value. find
// or create scores for these based on score and level.
// assign each the other values and save.  assume that params 
// of the form [{ owner:'sam', level:2, otherValue:'foo'}, ... etc.]
function findOrCreateScoresWith(params) {
    var scores = _.map(params, function(param) {
        return findOrCreateScore(param.owner, param.level, param.otherValue);
    });
    return Parse.Object.saveAll(scores);
}