Skip to content

Instantly share code, notes, and snippets.

@jonasfj
Created January 17, 2014 00:10
Show Gist options
  • Save jonasfj/8466037 to your computer and use it in GitHub Desktop.
Save jonasfj/8466037 to your computer and use it in GitHub Desktop.
Simple example of how to patch `AWS.Request` (on node.js) to return a promise. Monkey patching sucks, but this is at least somewhat safe, and makes the API much nicer to work with. An alternative would be to add a `.then` to `AWS.Request`, however, it would be hard to implement this in compliance with the A+ specification.
var aws = require('aws-sdk');
var Promise = require('promise');
/** Patch aws.Request to have a promise() method that returns a promise */
exports.patch = function() {
aws.Request.prototype.promise = function() {
var that = this;
return new Promise(function(accept, reject) {
that.on('complete', function(response) {
if (response.error) {
reject(response.error);
} else {
accept(response);
}
});
that.send();
});
};
};
@jonasfj
Copy link
Author

jonasfj commented Jan 17, 2014

This is inspired by comments to issue 13 on aws-sdk-js.

As my summary suggests, it is tempting to add .then to AWS.Request... But I'm not exactly sure how I would make the response object act as an A+ promise. If the complete event occurs before .then is called, you'll never be able to invoke handlers as required by the A+ specfication.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment