Skip to content

Instantly share code, notes, and snippets.

@aaronksaunders
Last active December 17, 2015 10:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronksaunders/083c7512342d1dde20c2 to your computer and use it in GitHub Desktop.
Save aaronksaunders/083c7512342d1dde20c2 to your computer and use it in GitHub Desktop.
used promises with Appcelerator Titanium @see http://documentup.com/kriskowal/q/
var Kinvey = Alloy.Globals.Kinvey;
var Q = require("q");
function handleButtonClicked(_event) {
var alert_data = null;
// if saved, then set properties
if (_event.source.id === "saveButton") {
alert_data = {
content : $.content.value,
title : $.title.value,
location_id : $.location_id,
photo_id : $.photo_id,
};
// alert save location
Q.fcall(function() {
console.log("save the location");
if ($.location) {
return deferredSave(_params, "Location").then(function(_resp) {
$.location = $.location || {};
$.location.entity = _resp.model;
});
}
}).then(function() {
console.log("save the photo");
if ($.photo) {
return deferredSave(_params, "Photo").then(function(_resp) {
$.photo = $.photo || {};
$.photo.entity = _resp.model;
});
}
}).then(function() {
console.log("save the alert include the location and photo object if exists");
return deferredSave(alert_data, "Alert").then(function(_resp) {
$.alert = $.alert || {};
$.alert.entity = _resp.model;
});
}).then(function() {
// all is well, so just close the window and be happy!!
setTimeout(function() {
$.mainWindow.close();
}, 200);
}, function error(e) {
// Any error that occurred in the previous execution
// scope will fall down to here for us to manage
alert(e);
// all is NOT well, but need to close window anyway
setTimeout(function() {
$.mainWindow.close();
}, 200);
});
} else {
$.mainWindow.close();
}
}
/**
* here we have modified the save method to work with promises so we can
* chain the asynchrous calls together in a more manageable process
*/
function deferredSave(_params, _object_type) {
var deferred = Q.defer();
var _object = new Kinvey.Entity(_params, _object_type);
_object.save({
success : function(_model) {
// location is the saved entity.
debugger;
deferred.resolve({
success : true,
model : _model
});
},
error : function(error) {
// Failed to save location.
// e holds information about the nature of the error.
debugger;
deferred.reject({
success : true,
model : null,
errorCode : error.code,
errorMsg : error.message
});
}
});
return deferred.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment