0

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);
        }
    });
};
  • There are all sorts of ways to address this, such as promises and async/await, but unless the APIs you're using are already returning promises the simplest solution is to add a callback argument to `getCentroids`, e.g. `function getCentroids(callback)` and then invoke that callback with the relevant error or data rather than trying to return it. You'd then call `getCentroids` with a callback function that performs your `res.send`. – skirtle Oct 22 '17 at 16:16
  • Thank you Skirtle, I've added the callback parameter to my function, i am unsure what you mean by invoking the callback rather than returning it – jon.nicholssoftware.com Oct 22 '17 at 16:29
  • Although yes, this question could technically be marked as duplicate because I did need to bake async and await functions to my code. On further investigation I discovered that only node version 7+ supports async functionality and that there are node modules designed to compensate for this. https://stackoverflow.com/questions/37815790/syntaxerror-unexpected-token-function-async-await-nodejs – jon.nicholssoftware.com Oct 22 '17 at 16:53
  • seeing as how the answer to the question is to for example upgrade my node versions, and then to use the async and await functionality that this question was marked as duplicate for, I would request that this post be unmarked as duplicate, and I am rephrasing the title – jon.nicholssoftware.com Oct 22 '17 at 16:54
  • The linked duplicate does not say that you have to upgrade Node. It discusses various approaches to solving this kind of problem, of which async/await is just one. The callback approach I suggested is also discussed in the accepted answer to that question. – skirtle Oct 22 '17 at 17:00
  • Fair enough, Thank you for the learning opportunity. This has been a great help Skirtle – jon.nicholssoftware.com Oct 22 '17 at 17:02

0 Answers0