Invoking many OpenWhisk actions from another one
I have a project where I need to store a number of items into a data store. I have an OpenWhisk action that stores the items so I wrote an action that takes advantage of the OpenWhisk JS client library to do invoke my store action once for each item in an array that this action receives.
This is the JavaScript code that I used:
"use strict";
const openwhisk = require('openwhisk');
async function main(params) {
if (!params.items) {
return {error: "No items"}
}
const action = "my_api/store")
const ow = openwhisk();
console.log(params.items.length + " items to be invoked")
let actions = params.items.map(function (item) {
return ow.actions.invoke({actionName: action, params: {item: item}});
});
try {
const responses = await Promise.all(actions);
} catch (err) {
console.error('Error invoking actions', err)
return Promise.reject({error: err});
}
console.log(actions.length + " actions invoked")
return {number_stored: actions.length}
}
exports.main = main;
This is a NodeJS v8 action (--kind nodejs:8 when creating via wsk) and does two things: create an actions array of all the invoke() calls for the items via the magic of map() and then it uses Promise.all() to execute them.
The actions are invoked in non-blocking mode which means that this action doesn’t need to wait for them to finish and so it returns quickly and then OpenWhisk goes about its business storing my items to the database.
Once in the database, I can use a trigger to invoke another action to do something with the data safe in the knowledge that it’s been saved securely.