Async Module

To support asynchronous scripting, a callback function done is provided. It has to be called from the custom script at the right time, normally when the code execution is finished. In a typical asynchronous scripting, it is called from within a special function where all the asynchronous executions end up with. The example below shows how to use the Async scripting.

Asynchronous Example

The following sample code shows how to add a piece of async JavaScript code to customize the response data. It uses a Node module async and the series() function to send requests to two websites in series and asynchronously waits for the responses to come back. After both of the responses are received from the two websites, the callback function function(err, results) is called, and the statusCode of the two responses are to be added to the response object. The done() callback is then called inside this function to notify the Microflow® logic that the running of this custom JavaScript is done, with the modified response being returned back.

var _ = require('lodash');
var async = require('async');
var request = require('request');
async.series([
function(callback){
	request('http://www.outlook.com', 
	function (error, response, body) {
		if (!error && response.statusCode == 200){
       			callback(null,response.statusCode);
     		}
  		});
	},
function(callback){
	request('http://www.yahoo.com', 
	function (error, response, body){
		if (!error && response.statusCode == 200){
			callback(null,response.statusCode);
     		}
  		});
	}],
function(err, results){
	res.body = {
		raw: res.body,
		total: res.body.length,
		vendor: 'TIBCO',
		result: results
	};
	done(res);
	}
);

After pushing the configured stage and running the Microflow application, query Microflow_endpoint/pet/findByStatus?status=pending, you can get the result as shown.