Hello, made the implementation of the method that works with the expectation of an event into a separate module. During page rendering, this method is called to get the parameters. Parameters are not returned. How to properly organize this task in my case?

index.js

var vk = require('./lib/vk.js'); app.get('/vk', function(req, res) { res.render('home',{ vk: vk.getMessages('wall.get', {'owner_id' : 456475864535})}); }); 

vk.js

  var VK = require('vksdk'); var vk = new VK({ 'appId': 5364746354, 'appSecret': 'fxgdhfdfs', 'language': 'ru' }); exports.getMessages = function (req,params) { vk.setSecureRequests(true); vk.request(req,params); vk.on('done:wall.get', function (_o) { return "privet"; // даже это не выводит console.log(JSON.stringify(_o, null, 4)); return _o; }); }; 
  • one
    The vk.getMessages () function does not return anything to you, if only because it simply does not have a return However, in reality, the problem is asynchronous: you have a res.render called before the vk.request request arrives. You need to pass the callback to getMessages , call it inside the done:wall.get handler done:wall.get , and call res.render() - Yaant already in it
  • Yes, it was worth the very thought, I decided that there is some generally accepted solution and design for this case. - Egor Mikheev
  • The conventional solution is just callbacks. :) Well, or promises. - Yaant

1 answer 1

Working option. index.js

 app.get('/vk', function(req, res) { vk.getMessages('wall.get', {'owner_id' : 34245436756},res); }); 

vk.js

 exports.getMessages = function (req, params, res) { vk.setSecureRequests(true); vk.request(req, params); vk.on('done:wall.get', function (_o) { res.render('home', {vk: JSON.stringify(_o, null, 4)}); //console.log(JSON.stringify(_o, null, 4)); }); };