used promises with Appcelerator Titanium @see http://documentup.com/kriskowal/q/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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