在nodejs中同步运行一个进程

时间:2013-03-12 06:46:20

标签: node.js synchronization child-process

我试图点击2个网络服务并得到他们的回复。应该并行命中Web服务,而Node.js异步执行。 childprocess.spawn也表现异步。任何关于如何从相同的Node.js代码并行打击两个Web服务的想法都会非常有用。

1 个答案:

答案 0 :(得分:0)

像robertklep建议async是要走的路

并行Web请求

/**
* Fetches both goole and yahoo at the same time, but waits until both 
* are done before returning
**/
var async = require('async')
var request = require('request')
var inspect = require('eyespect').inspector()
doParallel(function (err) {
  if (err) {
    inspect(err, 'error running parallel tasks')
  }
  inspect('********************************************************************')
  inspect('done with parallel tasks')
})
function doParallel(callback) {
  async.parallel([
    // fetch google.com
    function (cb) {
      var url = 'http://www.google.com'
      request(url, function (err, res, body) {
        if (err) {
          return cb({
            message: 'error getting google.com',
            url: url,
            error: err
          })
        }
        inspect(res.statusCode, 'google response status code')
        inspect(body, 'google response body')
        cb()
      })
    },

    function (cb) {
      var url = 'http://www.yahoo.com'
      request(url, function (err, res, body) {
        if (err) {
          return cb({
            message: 'error getting google.com',
            url: url,
            error: err
          })
        }
        inspect(res.statusCode, 'yahoo response status code')
        inspect(body, 'yahoo response body')
        cb()
      })
    }
  ], callback)
}

系列Web请求

var async = require('async')
var request = require('request')
var inspect = require('eyespect').inspector()
doSeries(function (err) {
  if (err) {
    inspect(err, 'error running parallel tasks')
  }
  inspect('********************************************************************')
  inspect('done with parallel tasks')
})
/**
 * Fetch google first, wait for it to finish, and then fetch yahoo
 **/
function doSeries(callback) {
  async.series([
    // fetch google.com
    function (cb) {
      var url = 'http://www.google.com'
      request(url, function (err, res, body) {
        if (err) {
          return cb({
            message: 'error getting google.com',
            url: url,
            error: err
          })
        }
        inspect(res.statusCode, 'google response status code')
        inspect(body, 'google response body')
        cb()
      })
    },

    function (cb) {
      var url = 'http://www.yahoo.com'
      request(url, function (err, res, body) {
        if (err) {
          return cb({
            message: 'error getting google.com',
            url: url,
            error: err
          })
        }
        inspect(res.statusCode, 'yahoo response status code')
        inspect(body, 'yahoo response body')
        cb()
      })
    }
  ], callback)
}