I chose node.js for my task because it have official Google API client library and is natural to work with JSON. But I'm struggling with asynchronous idioma and the guides I found on the internet doesn't cover my case.
So, in this example I'm trying to read the contents of two files and pass them to a method:
var fs = require('fs');
// Some more unrelated vars here
function readFiles(callback) {
fs.readFile('./refresh_token', 'utf8', function(err,refreshToken) {
if (err) throw err;
callback(refreshToken);
});
fs.readFile('./access_token', 'utf8', function(err,accessToken) {
if (err) throw err;
callback(accessToken);
});
};
function handleResults(refreshToken, accessToken) {
oauth2Client.setCredentials({
refresh_token: refreshToken,
access_token: accessToken
});
proceedNext(oauth2Client);
};
function proceedNext(credentialsObject) {
// do some more job
};
readFiles(handleResults);
Obviously it's not working because I'm doing two callbacks on the first position. But, what is the correct way (node.js way) to perform two methods asynchronously, pass the both results to the handling method, and then proceed further only after this been completed?
I tried something like this:
function readFiles() {
fs.readFile('./refresh_token', 'utf8', function(err,refreshToken) {
if (err) throw err;
fs.readFile('./access_token', 'utf8', function(err,accessToken) {
if (err) throw err;
oauth2Client.setCredentials({
refresh_token: refreshToken,
access_token: accessToken
});
proceedNext();
});
});
};
And it worked after playing with global variables a bit, but I think this is a terrible, terrible idea and it's undermines the point of node.js. I'm looking for a correct way to do this, and I feel after passing this wall everything else should start making sense in node.js
asyncnpm module: caolan.github.io/async