简体   繁体   中英

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.

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 recognizeFaces method 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM