What is the easy way to access the callback function arguments outside of it?

Problem

My code is like this,

var jenkins = require('jenkins')('http://192.168.1.5:8080');
var job_name = undefined;

jenkins.job.list(function doneGetting(err, list) {
    if (err) throw err;
    job_name = list[0].name;
});

jenkins.job.get(job_name, function(err, info){
    if (err) throw err;
    res.render('index', {
         title: 'Jenkins API',
         job_name: job_name,
         job_info: info
    })
});

My problem is I am not able to get the value of job_name because it is inside the callback. I am trying to find the solution for this. Though lot of questions already present about callbacks am not able to find the solution. Sorry for that.

Thanks in advance.

Problem courtesy of: karthikeayan

Solution

You can simply move your jenkins.job.get inside jenkins.job.list callback

jenkins.job.list(function doneGetting(err, list) {
    if (err) throw err;
    job_name = list[0].name;

    jenkins.job.get(job_name, function(err, info){
        if (err) throw err;
        res.render('index', {
             title: 'Jenkins API',
             job_name: job_name,
             job_info: info
        })
    });
});

there are other solutions, like to use a function

jenkins.job.list(function doneGetting(err, list) {
    if (err) throw err;
    job_name = list[0].name;

    getJob(job_name);
});

function getJob(job_name) {
    jenkins.job.get(job_name, function(err, info){
        if (err) throw err;
        res.render('index', {
             title: 'Jenkins API',
             job_name: job_name,
             job_info: info
        })
    });
}

it depends by your pattern, or module or script complexity.

Solution courtesy of: chumkiu

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.