How to send json, after async function complete

I'm using expressjs. I have a router:

exports.index = function(req, res){

  if(req.param('name')) {

    var simpleParser = require('../tools/simpleParser');
    var result = simpleParser.images(req.param('name'));

    // how i can get result from simpleParser.images after it complete?

    res.json(result);

  }

  res.render('goods');

};

An i have a simpleParser.images:

module.exports = {
    images: function (url) {
        if (url) {

            var request = require('request'),
                cheerio = require('cheerio');

            request({
                uri: url,
                method: 'GET',
                encoding: 'binary'
            }, function (err, res, body) {

                var tmp = [];

                body = new Buffer(body, 'binary');

                var $ = cheerio.load(body);

                $('.products-listing li a').each(function () {
                    var link = $(this).find('img').attr('src');
                    tmp.push(link);
                });

                // How i can send tmp to router, when it complete?

            });

        }
    }
};

When i asking page with ?name it return null, because request in simpleParser.images work async. How i can subscribe to result of simpleParser request function, and send json after it complete?

Like many node modules, you can provide a callback in your own utility functions. Your simpleParser.images function is not synchronous, as it uses the request module. You can have your simpleParser.images function accept a callback that will be called upon the completion of the network request and some data parsing.

var request = require('request'),
  cheerio = require('cheerio');

module.exports = {
  images: function (url, callback) {
    if (!url) callback(null, null);

    request({
      uri: url,
      method: 'GET',
      encoding: 'binary'
    }, function (err, res, body) {
      if (err) callback(err);
      var tmp = [];
      body = new Buffer(body, 'binary');
      var $ = cheerio.load(body);
      $('.products-listing li a').each(function () {
        var link = $(this).find('img').attr('src');
        tmp.push(link);
      });

      // Here we have the data and can pass it in the callback
      callback(null, tmp);
    });
  }
};

Then you essentially have your own function that can be performed asynchronously. Then in your express route, that is async as well, so just plug in your new function

if (req.param('name'))
  simpleParser.images(req.param('name'), function (err, images);
    res.json(images);
  });
} else {
  res.render('goods');
}