UPD. в приницпе разобрался с асинхронностью. но теперь не совсем понятно, как надо организовывать приложение.
например, подключение к базе — это отдельный модуль, который возвращает объект бд?
измененный модуль:
/*
* GET friends
*/
var https = require('https'),
Db = require('mongodb').Db,
Server = require('mongodb').Server;
var client = new Db('data', new Server('127.0.0.1', 27017, {})),
coll;
client.open(function (err, pClient) {
pClient.collection('friends', function (err, collection) {
coll = collection;
});
});
function resSend(res) {
coll.find().toArray(function (err, docs) {
res.send("{ response: " + JSON.stringify(docs) + " }");
});
}
exports.get = function (req, res) {
coll.count(function (err, count) {
if (count === 0) {
https.get('https://api.vk.com/method/friends.get?fields=uid,first_name,last_name&access_token=' + global['access_token'], function (d) {
var chunk = '';
d.on('data', function (data) {
chunk += data;
});
d.on('end', function () {
coll.insert(JSON.parse(chunk).response);
resSend(res);
});
}).on('error', function (e) {
console.error(e);
});
} else {
resSend(res);
}
});
};