0

I am trying to push some values to array by fetching data from Jenkins APIs, like below.

buildNum = 14;
async.waterfall([
function(callback){
for ( var i = buildNum; i > (buildNum-5); i--) {
  (function(){
        jenkins.build_info('BuildDefinitionRequest', i, function(err, data) {
            if (err){ return console.log(err); }

                var tmpObj = {};

                tmpObj.jobID = data.fullDisplayName;
                tmpObj.result = data.result;
                tmpObj.dateTime = data.id;
                console.log(tmpObj);

                finalArray.push(tmpObj);

            });
        })();
    }
    callback(null, finalArray, 1);
  },
  function(finalArray, value, callback){
    console.log(finalArray, value);
    callback(null, 'done');
  }
  ],function(err, result){
  });

But "callback(null, finalArray, 1);" is getting called before the for loop finish its execution. When I am printing the value of "finalArray" inside the for loop I am able to see all the values.

1 Answer 1

3

Technically the for loop has finished executing, but the jenkins.build_info calls haven't. You cannot make async calls inside of a for loop like that and expect the for loop to only finish after all the calls are complete. You're already using async, so this is an easy fix. I would do something like this:

var buildNum = 14;
var builds = [];

// just builds a collection for async to operate on
for(var i = buildNum; i > (buildNum - 5); i--) {
  builds.push(i);
}

var finalArray = [];
async.each(builds, function(build, next) {
  jenkins.build_info('BuildDefinitionRequest', build, function(err, data) {
    if (err) { next(err); }

    var job = {
      jobID: data.fullDisplayName,
      result: data.result,
      dateTime: data.id
    };

    finalArray.push(job);
    next();
  });
}, function(err) {
  // this won't be called until all the jenkins.build_info functional have completed, or there is an error.
  console.log(finalArray);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.