Reputation: 392
I am fairly new to the world of Javascript promises and am having issues implementing the following:
var Promise = require('bluebird');
var jenkinsapi = require('jenkins-api');
var asyncJenkinsAPI = Promise.promisifyAll(jenkinsapi);
var jenkins = asyncJenkinsAPI.init("http://<user>:<password>@localhost:8080");
app.get('/api/servers', function(req, resp) {
SavedJob.find({})
.then(function(jobs) {
return Promise.all(jobs.map(function(job){
// do two calls with each job.name
// build new data with the result of the two calls
// return new data to next part of chain
var job_status = jenkins.job_info(job.name, function(err, jobData) { return jobData; });
var build_info = jenkins.last_build_info(job.name, function(err, buildData) { return buildData; });
return {task_name: job_status.name,
status: STATUSMAP[job_status.color] || "UNKNOWN",
latest_build:
{
build_date: build_info.timestamp,
build_status: build_info.result,
build_number: build_info.number,
build_url: build_info.url
}
};
}));
})
.then(function(results){
console.log(results);
});
});
How can I best implement making two asynchronous calls inside the Promise.all()
with each job.name
and have the set of results at the end?
Upvotes: 0
Views: 181
Reputation: 664405
After having promisified jenkins, you will need to use the new promise-returning methods:
var job_promise = jenkins.job_infoAsync(job.name);
var build_promise = jenkins.last_build_infoAsync(job.name);
(you might want to pass {suffix: "_async"}
as an option to promisifyAll
for nicer method names).
Then combine those two promises (Promise.all
/Promise.props
/Promise.join
):
return Promise.join(job_promise, build_promise, function(job_status, build_info) {
return {
task_name: job_status.name,
status: STATUSMAP[job_status.color] || "UNKNOWN",
latest_build: {
build_date: build_info.timestamp,
build_status: build_info.result,
build_number: build_info.number,
build_url: build_info.url
}
};
});
The rest of your code (mapping, chaining) is working fine.
Upvotes: 1