callbackAsync.Map不工作
我对callback比较陌生,并且在获取下面的代码的过程中不成功。 我已经使用async.map函数将每个Web调用的数据返回到相应的页面。 不过,即使callback(data)
之前的console.log(data)
callback(data)
正在返回网页的html,我的console.log(return)
也会返回[ , undefined]
。 这是我的代码:
var http = require("http"), fs = require("fs"), page, chap, ot, async = require("async"); ot = fs.open('ot.txt', 'w'); page = "test"; chap = 2; function getData(url, callback) { var data = ""; var options = { host: "rs.au.com", port: 80 } options.path = url; console.log("request sent to: http://" + options.host + options.path); var req = http.request(options, function(res) { console.log("Response received " + res.statusCode); res.on('data', function(chunk) { data += chunk; }); res.on('end', function(e) { console.log(data); callback(e, data); }); }).end(); } function main() { var pathArr = []; for ( var i = 1; i <= chap; i++ ) { pathArr[i] = "/".concat(page, "/", i, ".html"); } async.map(pathArr, getData, function(err, result) { console.log("The result is :" + result); }); } main();
任何人都可以请指出为什么我的代码不工作,我怎么能纠正它?
非常感激!
编辑:布兰登Tilley的回应后,我修改callback函数从callback(data)
callback(e, data)
,但是我没有得到从最后的console.log
输出现在没有反应。
asynchronous库假定你的callback符合标准的Node.jscallback签名,这是callback(err, others...)
。 由于您将data
作为第一个parameter passing,因此Async会认为是错误的。 你应该使用callback(e, data)
来代替(因为在没有错误的情况下e
将是null
的)。
[更新]
另一个问题是你的数组不正确。 因为i
从1开始并上升到chap
, pathArr[0]
是不确定的。 更改:
pathArr[i] = "/".concat(page, "/", i, ".html");
至
pathArr[i-1] = "/".concat(page, "/", i, ".html");
- 处理NodeJSasynchronous行为
- node-horsemanasynchronous不起作用?
- 将parameter passing给callback node.js
- Coffeescript与callback和简化的error handling
- Node.js:res.redirect(“back”)得到错误('不能在发送之后设置头部')。
- 为什么zlib.deflate(buf,callback)是asynchronous的?
- 查询数据库时出现asynchronous瀑布问题
- node.js,以同步的方式在循环中一个接一个地执行mysql查询
- Node.js:你如何处理循环中的callback?