I want to make a module that outputs a set of metrics about the health of my application, such as background queue lengths, response time to service dependencies etc. This is Node JS using Deferred:
var metrics = {
queueLength: function(def) {
// .. Do some stuff to resolve the queue length ..
def.resolve(45); // Example
}
// ... more metrics
}
for (i in metrics) {
def = deferred();
metrics[i](def);
promiselist.push(def.promise);
def.promise(function(result) {
metrics[i] = result;
}
}
return deferred(promiselist)(function(result) {
console.log('All metrics loaded', result, metrics);
});
This produces the output
Metrics loaded [ [Function] ] { queueLength: [Function] }
When I would have expected:
Metrics loaded [ 45 ] { queueLength: 45 }
I think I'm doing two things wrong but don't know how to correct them 'properly':
- The
return deferred([array of promises])(group promise)
idea doesn't seem to work - I've just realised
def
is getting reused on each iteration so if I had multiple metrics it would probably only track the last one.