One OpenWhisk Action Calls Another

Working with openwhisk, it’s easy to create many isolated actions and build them up into sequences; the output of one action is passed to the next action in the sequence. In my case, I wanted one action to spawn potentially many other actions. I had to look up how to do it and here it is so I can look it up more quickly next time!

The use case is that my app makes a call to an API and then we process each of the items in the response with its own action. In my code example I have replaced the API call with a hardcoded API so we can focus simply on invoking another action for each iteration in a loop. Here’s the first action:

function main(params) {

  return new Promise(function(resolve, reject) {

    var openwhisk = require('openwhisk');
    var list = ['Susie', 'Freya', 'Ruth'];
    var ow = openwhisk();

    var actions = list.map(function (item) {
      return ow.actions.invoke({actionName: "invoker/hello", params: {name: item}});
    });

    return Promise.all(actions).then(function (results) {
        console.log(results);
        return resolve({payload: "All OK"});
    });
  });
}

This file is called first.js (naming things is hard) and for each of the names in the array, it adds an instance of the invoker/hello action to the actions array using the OpenWhisk npm module (available on OpenWhisk by default). Once we’ve got all the action invocations we want added to the list (they’re all promises in their own right), we use Promise.all() to make them happen and finally resolve our original promise with a success payload.

The second action isn’t terribly exciting but does allow you to see the moving parts actually moving. Here is the code:

function main(params) {
    console.log(params);
    var message = "Hello " + params.name;
    return {payload: message}
}

All that happens here is that we log the incoming parameters so that you can see the data arriving, then build a message to return as our output. I found this step – moving away from sequences and potentially fanning a workload out over many actions – difficult to narrow down at first. Huge thanks goes to @thomasj for giving me a working example that I used to create the above. When project maintainers help, it’s polite to share as widely as possible so that they don’t have to create the same examples over and over so hopefully this will help others as well as future-me who will surely be back to read this post at some point!

2 thoughts on “One OpenWhisk Action Calls Another

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.