I'm working on a Meteor application which integrates a user's contacts from external sources (Google in the case of this example). I'm currently writing the server side code to retrieve this data and send it to the client.
I figured using promises to do this made sense due to the asynchronous manner of requests. So I have getContacts
which sends the request to the Google API, and processContacts
which processes and formats the response data:
getContacts = function (accessToken) {
return new Promise(function (resolve) {
httpRequest.get({
url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',
auth: {
'bearer': accessToken
},
headers: {
'GData-Version': 3.0
},
}, function (err, res, body) {
resolve(body);
});
});
}
processContacts = function(googleContacts) {
return new Promise(function(resolve) {
const contacts = JSON.parse(googleContacts).feed.entry;
const allContacts = [];
const groupedContacts = { conflicts: [], new: [] };
...
...
resolve(groupedContacts);
});
}
I have a Meteor method google.contacts.import
which is called synchronously from the client, and because all of this is asynchronous I'm using a future to force the client to wait for the call to finish:
Meteor.methods({
'google.integration.import'(orgId) {
check(orgId, String);
const user = Users.getOne(Meteor.userId());
let fut = new Future();
getContacts(user.services.google.accessToken)
.then(processContacts)
.then(function(contacts){
fut.return(contacts);
})
.catch(function(err){
console.log('error! :' + err);
});
return fut.wait();
},
})
This all works fine, but it seems...messy or somewhat convoluted. I'm relatively new to Javascript and ES6 in particular so I feel I could definitely improve this. Am I correct to be using promises here? I guess they probably aren't necessary in the case of processContacts
. I also realize this is lacking in terms of error checking/reporting.
Any help or guidance is appreciated!