Created
January 17, 2014 00:10
-
-
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.
This file contains hidden or 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 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(); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is inspired by comments to issue 13 on aws-sdk-js.
As my summary suggests, it is tempting to add
.then
toAWS.Request
... But I'm not exactly sure how I would make the response object act as an A+ promise. If thecomplete
event occurs before.then
is called, you'll never be able to invoke handlers as required by the A+ specfication.