Add promises support
inakiabt opened this issue · comments
Maybe using https://github.com/kriskowal/q
The Parse promises implementation is very good too, but I guess is very coupled to the Javascript SDK.
👍
Jason, I've made an initial approach to support Promises using https://github.com/kriskowal/q here: https://github.com/inakiabt/RESTe
Also, I've "titaniumified" the library.
To build the module, you have to run:
npm install
npm install --save-dev grunt grunt-titaniumifier # not sure if it's required
titaniumifier --out dist
Then, add it as a new module in a Titanium app and that's it:
<modules>
<module platform="commonjs" version="1.0.0">RESTe</module>
</modules>
Here's a sample app.js:
ENV_DEV = true;
var api = require("RESTe");
api.config({
timeout: 4000,
url: "http://jsonplaceholder.typicode.com/",
_requestHeaders: {
"Content-Type": "application/json"
},
methods: [{
name: "getPosts",
post: "posts"
}, {
name: "getPostById",
get: "posts/<postId>"
}, {
name: "getComments",
post: "comments"
}, {
name: "getCommentsById",
get: "comments/<commentId>"
}]
});
// Use then and fail
api.getPosts().then(function(response){
Ti.API.debug('POSTS:', JSON.stringify(response));
}).fail(function(error){
console.error(response);
});
// Test fails
api.getPostById({
postId: 8282390
}).fail(function(error){
console.error('By ID ERROR error');
console.error(JSON.stringify(error));
});
// Test by id
api.getPostById({
postId: 10
}).then(function(response){
Ti.API.debug('By ID:', response);
}, function(error){
console.error('By ID error');
console.error(JSON.stringify(error));
});
// Test no promises -> original callbacks
api.getPostById({
postId: 5
}, function(response){
Ti.API.debug('By ID callback:', response);
});
// Test nested promises
api.getCommentsById({
commentId: 10
}).then(function(comment){
Ti.API.debug('COMMENT:', comment);
return api.getPostById({
postId: comment.postId
});
}).then(function(post){
Ti.API.debug('[nested] POST:', post);
});
// Test use of Q in app
var Q = api.Q;
Q(17).then(function(postId){
return api.getPostById({
postId: postId
});
}).then(function(post){
Ti.API.debug('[using Q] POST:', post);
});
Let me know what do you think about it.
Thanks - appreciate the effort. I've added the Titaniumifer support and published to npm, credited you on the commit. Will look at the promises stuff as a separate thing but have some more changes to make first.
Appreciate the work.
Ok. Just let me know if you need a hand.
Thanks.
May I suggest to use bluebird instead of q?
I second the bluebird suggestion
- 1 on bluebird suggestion
no on promises?
Yes - not adding it at this time.