Monday 10 April 2017

node.js async callback error on queue.drain

I'm trying to use a callback to indicate when all the async workers are complete, but I'm getting the dreaded "TypeError: callback is not a function". I would like to individually process each element in data, and on completion, have queue.drain to send the callback(data) to refreshData on completion. I've been readying the async documentation, but clearly i'm not getting something. Any assistance would be greatly appreciated!

function refreshData(postData, callback) {

    var options = {
        host: 'www.myhost.com',
        port: 443,
        path: '/pulldata,
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        }
    };

    var req = https.request(options, function(res) {
       var headers = res.headers
       var d = '';
       res.setEncoding('utf8');
       res.on('data', function (chunk) {
           d = d + chunk;
       });
       res.on('end', function() {
           if (res.statusCode == '200') {
               data = JSON.parse(d);

                queue = async.queue(function (task, cb) {
                    processData(task,cb);
                 },1); 

                 //this is were the errors are
                 queue.drain = function() {
                    callback(data)
                  };

                 for(i=0; i<data.length; i++) {
                     queue.push(data[i],'');
                  }

            } else {
                 callback(false)
            }
        }); 

    });

    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });

    // write data to request body
    req.write(postData);
    req.end();  
}   



via leo

No comments:

Post a Comment