Understanding Promises

When I started programming with Node.js, I complained a lot about nesting asynchronous in anonymous functions and the spaghetti code that it leads to. Of course I use my years of programming experience to still write good code, but its harder. My friends on the SDK team would tell me to use promises as it makes the async responses easier to manage. You know how it is, you take a look at new technology and the first time round you just about get your head around it. The second time you start to feel comfortable. The third time is when you can safely use it in code that you are sharing and then onwards you master it.

You may have seen the recent announcement that the AlchemyAPI service was being retired. Alchemy Vision had long been superseded by Watson Visual Recognition, as mentioned in my last blog Alchemy News has been superseded by Watson Discovery, and Alchemy Language by Natural Language Understanding. We already had Node-red nodes for Visual Recognition and Discovery, we now also have a node for Natural Language Understanding.

Application of Promises

I was at stage 3 in my exploration of promises in Node.js, so I decided to make use of promises in coding up the node for Natural Language Understanding. You can take a look at the code in GitHub.

I wrapped a promise around the async call to the Watson service, which tidied the code a little. After publishing I got thinking and now that I am at stage 4, I realised that all the synchronous function calls I used to perform configuration checking and parameter building could also have been wrapped in promises. Not such a big deal in the Natural Language Understanding node, but for some of our other nodes, where we have mix of multiple async and sync processing, it would make a big difference.

Watson Conversation Intents

The set of methods behind the Workspace management API for the Watson Conversation service is growing. A recent release gave us methods to manipulate Intents and Intent Examples through the API. These capabilities have been added to the Node-RED node for Conversation Workspace Management.

Now this is a complicated node, as it was already allowing you to create, list, update and delete workspaces. The create and update capabilities require you to send a json structure as a file or a data stream or a json object on msg.payload. The calls to manipulate this json structure are a mix of async and sync functions. Perfect for promises. So first, I wrapped all the existing code, sync and async into promises. Once I got that working I then rolled in the functionality for management of Intents and Intent Examples. You can take a look at the result in GitHub. The result of applying promises in this node means that adding new capability such as Entity management, which might be released next, becomes very straight forward. Stay tuned for that.

Join The Discussion

Your email address will not be published. Required fields are marked *