I am writing the Cloud function for Parse whose purpose is to update my database with a provided array of data objects. The main problem are the nested promises, which doesn't look right. Any help to refactor this code or any other critiques?
/**
* Updating multiple object arrays:
* Look for object with the same idKey and update with supplied data or create new if none is found
* Expect Data {schema: <schema_name>, idKey: <name_of_id_key>, data: <object_array>}
*/
Parse.Cloud.define("updater", function(request, response) {
var _ = require('underscore');
var schema = request.params.schema,
idKey = request.params.idKey,
objectArray = request.params.data;
var Class = Parse.Object.extend(schema),
parseObject,
id,
query;
_.each(objectArray, function(dataObject){
id = dataObject[idKey];
if (!id) return response.error("Supplied Object " + dataObject + " has no id Key '" + idKey + "' set!");
// now query for the same idKey
query = new Parse.Query(Class);
query.equalTo(idKey, id);
query.find().then(
function(array){
if(array) {
// found at least one object - take the first
parseObject = array[0];
// use the new dataObject to update parseObject
parseObject.set(dataObject);
parseObject.save().then(
/*
* should this go outside the promise?
*/
function(object){
// success
},
function(error){
return response.error(error);
});
} else {
// nothing found - create new
parseObject = new Class(dataObject);
parseObject.save().then(
function(object){
// success
},
function(error){
return response.error(error);
});
}
}
);
parseObject = new Class(dataObject);
parseObject.save().then(
function(object){
// success
},
function(error){
response.error(error);
});
});
response.success("Success!");
});
response.success
right away, because it doesn't wait for all the save operations to finish. And if one of those do fail, it'll callresponse.error
- except, as mentioned, I imagine the response object has long since been resolved successfully, and I imagine it can only be resolved once. And even if one save fails, the code keeps going with the rest of the objects. It all seems kinda suspect to me. \$\endgroup\$.then
- have to re-think it ... \$\endgroup\$