Using Async and Promises in OpenWhisk
Occasionally you may encounter a need to define an action in OpenWhisk where you have to perform a number of steps in a specific order and return the result asynchronously. This is rather simple to achieve in OpenWhisk by using async.series wrapped in a Promise. The following code example shows you how to do this. The key aspects to keep in mind are that in each series function you call the callback and indicate whether or not the current function has succeeded or encountered an error. Once all the functions in the series have been called the last function is called and it is at this point where you handle the promise. In the event an error has occurred somewhere the reject function will get called and if the function calls in the series were successful, then the resolve function will be called.
// Using async with promises function main(params) { var async = require("async"); return new Promise(function (resolve, reject) { async.series([ function (callback) { var condition = true; var error = {message: 'failed'}; var data = {value: 'myValue'}; // Do some stuff if (condition) { callback(null, data); } // error else { callback(error, null); } }, function (callback) { // Do more stuff here } ], function (error, results) { if (error) { reject({"error": error.message}); } else { resolve({"results": results.value}); } }); }); }