我试图打 2 个网络服务并得到他们的回应。Web 服务应该并行处理,而不是 Node.js 异步执行。childprocess.spawn
也表现异步。任何关于如何从相同的 Node.js 代码中并行访问两个 Web 服务的想法都会非常有帮助。
问问题
181 次
1 回答
0
就像 robertklep 建议的异步是要走的路
并行 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)
}
系列网络请求
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)
}
于 2013-03-12T07:16:17.360 回答