操作完成后执行function

我在节点JavaScript的工作,并试图在过去的循环完成时运行一个新的function。 在下面的代码中, // loop through objects in data, to process it用来表示数据的基本循环,数据被附加到数组中。

随着每个响应,z增加1。 但是,我经常发现z在数据处理之前有时会达到40。 我不能把z放入循环中,因为每个页面内都有很多对象。

任何人都可以提出一个方法,只增加z和循环完成后检查它等于40?

 var req = http.request(headers, function(response) { response.on('error', function (e) { // }) response.on('data', function (chunk) { // }); response.on('end', function() { // loop through objects in data, to process it z++ if (z == 40) { newFunction(values, totals) }; }); }) req.on('error', function(e) { // }) req.end(); 

我同意trincot,我会要求你更具体些。 但从我收集你可以尝试使用async.each()。 http://justinklemm.com/node-js-async-tutorial/

我希望这有帮助。

在每个响应的循环内,比较处理的对象数量和响应中的对象总数。 只有在达到该数字时才会增加z值。

 loop through responses loop through objects in single response if ( data.length === counter) { z ++; } counter ++; } if ( 40 === z ) { newFunction(values, totals); } } 

我推荐使用stream行的asynchronous模块中的async.timesSeries!

链接: https : //github.com/caolan/async#times

示例代码:)

 // Required NPM Modules var async = require('async') // Run Async Times Series Function // Will execute 40 times then make the final callback async.timesSeries(40, asyncOperation, asyncTimesCallback) /** * This is the primary operation that will run 40 times * @param {Number} n - Sort of like the index so if its running 40 times and its the last time its running its gonna be 39 or 40 not sure you may have to test that * @param {Function} next - Callback function when operation is complete see async times docs or example in this code */ function asyncOperation (n, next){ var req = http.request(headers, function(response) { response.on('error', function (e) { return next(e, null) }) response.on('data', function (chunk) { // }) response.on('end', function() { // loop through objects in data, to process it return next(null, 'some value?') }) }) req.on('error', function(e) { return next(e, null) }) req.end() } /** * This is run after the async operation is complete */ function asyncTimesCallback (err, results) { // Error Checking? if(err) { throw new Error(err) } // function to run wen operation is complete newFunction(results['values'], results['totals']) } /** * New Function The Callback Function Calls */ function newFunction(values, totals){ console.log('Values', values) console.log('Totals', totals) }