Created
December 24, 2015 03:20
-
-
Save benmccormick/470ed7b8c7d6b642a42f to your computer and use it in GitHub Desktop.
Converting callbacks to promises
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
//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