操作完成后执行功能

时间:2016-04-29 19:12:54

标签: javascript node.js

我正在使用节点JavaScript,并且在过去的循环完成时尝试运行新函数。在下面的代码中,// 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();

3 个答案:

答案 0 :(得分:1)

我同意trincot,我会请你更具体一点。 但是从我收集的内容中你可以尝试使用async.each()。 http://justinklemm.com/node-js-async-tutorial/

我希望这会有所帮助。

答案 1 :(得分:0)

在每个响应的循环内,将处理的对象数与响应中的对象总数进行比较。仅在达到该数字时增加z。

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

答案 2 :(得分:0)

我建议使用流行的异步模块中的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)

}