I have a node JS application, below is the controllers code. I would like the send back a response thru exports js. The response should be the result returned by "return JSON.stringify(res, null, 2);"
. The issue is that when I throw this in a debugger, the "res.send({ message: result });"
fires before the result variable is populated by "var result = getCentroids();"
. I believe this is due to the fact that the visual recognition REST API call is asynchronous, but i'm not sure how to compensate for this. I am using 2 technologies here.. Node JS Exports module, and IBM watson's visual recognition. Any help would be greatly appreciated. My goal is to send back the results using res.send but the problem is the res.send fires before the result variable is populated.
var Task = require("../models/tasks");
exports.addTask = function(req,res){
var result = getCentroids();
res.send({ message: result });
};
function getCentroids() {
//Begin Watson Code
var watson = require('watson-developer-cloud');
var fs = require('fs');
var visual_recognition = watson.visual_recognition({
api_key: 'MY-API-KEY',
version: 'v3',
version_date: '2016-05-20'
});
var params = {
images_file: fs.createReadStream('./Content/Images/test2.jpg')
};
var result = visual_recognition.classify(params, function (err, res) {
if (err) {
return err;
}
else {
//response = JSON.stringify(res, null, 2).replace(new RegExp("\"", "g"), '\'');
return JSON.stringify(res, null, 2);
}
});
};