Node.js 异步函数完成后如何发送json

Node.js 异步函数完成后如何发送json,node.js,asynchronous,Node.js,Asynchronous,我正在使用expressjs。 我有一个路由器: 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.

我正在使用expressjs。 我有一个路由器:

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');

};
我有一个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?

            });

        }
    }
};

当我询问带有?name的页面时,它返回null,因为simpleParser.images中的请求是异步工作的。如何订阅simpleParser请求函数的结果,并在完成后发送json?

与许多节点模块一样,您可以在自己的实用程序函数中提供回调。您的
simpleParser.images
函数不同步,因为它使用
request
模块。您可以让您的
simpleParser.images
函数接受回调,该回调将在完成网络请求和某些数据解析后调用

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);
    });
  }
};
然后,您基本上拥有自己的可以异步执行的函数。然后在你的 expressroute也是异步的,所以只需插入新函数即可

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