Search code examples
node.jsibm-watsonalchemyapi

Using Alchemy API Synchronously


I am attempting to write a pure function to use the Alchemy API with the watson-developer-cloud npm package, but I cannot figure out how to execute its calls synchronously. Is there an alternative method or package whereby I could receive its results synchronously? Blocking while the I/O is occurring is absolutely fine.


Solution

  • You can not do synchronous calls with the watson-developer-cloud npm module. What you can do is use Promises and mimic the synchronous model.

    The example below shows how to call the AlchemyVision recognizeFacesmethod using promises:

    var watson = require('watson-developer-cloud');
    var Q = require('q');
    
    var alchemy_vision = watson.alchemy_vision({
      api_key: '<api_key>'
    });
    
    // Creates a promise-returning function from a Node.js-style function
    var recognizeFaces = Q.denodeify(alchemy_vision.recognizeFaces.bind(alchemy_vision));
    
    var params = {
      url: 'http://si.wsj.net/public/resources/images/BN-BY925_mag041_OZ_20140318165119.jpg'
    };
    
    recognizeFaces(params).then(function (keywords) {
      console.log(JSON.stringify(keywords, null, 2));
    }).catch(function (err) {
        console.log('error:', err);
    });