Skip to content

Instantly share code, notes, and snippets.

@benmccormick
Created December 24, 2015 03:20
Show Gist options
  • Save benmccormick/470ed7b8c7d6b642a42f to your computer and use it in GitHub Desktop.
Save benmccormick/470ed7b8c7d6b642a42f to your computer and use it in GitHub Desktop.
Converting callbacks to promises
//Backbone.Model's save function is a function that takes callbacks
//for successful or failed saves.
//Normal usage
let model = new Backbone.Model();
model.save(null, {
success: function() {
alert('saved');
},
error: function() {
alert('failed to save');
}
});
//We can create a save function that takes a model and returns a Promise
function save(model) {
return new Promise(function(resolve, reject) {
model.save(null, {
success: resolve,
error: reject,
})
})
}
//new usage
save(model).then(function() {
alert('saved');
}).catch(function() {
alert('failed to save');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment