How to convert PJS.query to asynchronous

Dear All,

I am trying to execute a batch process to query the database. Batch will have hundreds of queries and tried to execute through Promise.all. But it still working as a top down approach only. But same Promise.all is working fine if we test with sample timer function instead of pjs.query.

IN the below code DoSomethingAsync() is called three timeswhich are not executed in parallel. It is executed one by one only. Kindly suggest a solution for resolving this issue

Code Reference:
var dateFormat = require(‘dateformat’);

async function DoSomethingAsync(){
return new Promise((resolve) => {
var Result1 = pjs.query(query1);
var Result2 = pjs.query(query2 based on Result1 result);
var Result3 = pjs.query(query3 based on Result2 result););
var FinalResult = pjs.query(query4 based on Result3 result););
resolve(FinalResult);
});
}

async function sampleAPI(req, res){
var globalContents=[];
var promises=[];
promises.push(DoSomethingAsync());
promises.push(DoSomethingAsync());
promises.push(DoSomethingAsync());
var ResultContent = pjs.fiber.runPromise(Promise.all(promises));
res.send(ResultContent);
}

exports.run=sampleAPI;

The general approach to do something like this is as follows:


function grids() {
  pjs.defineDisplay("display", "grids.json");

  var queries = [];
  queries.push(queryPromise("SELECT productCode, productName FROM products"));
  queries.push(queryPromise("SELECT customerNumber, customerName FROM customers"));

  // Run queries simultaneusly
  var results = pjs.fiber.runPromise(Promise.all(queries));

  display.productsGrid.replaceRecords(results[0]);
  display.customersGrid.replaceRecords(results[1]);

  display.mainScreen.execute();
}


function queryPromise(sql) {

  return new Promise((resolve, reject) => {
    try {
      var result = pjs.query(sql);
      resolve(result);
    }
    catch(err) {
      reject(err);
    }
  })

}

exports.default = grids;

You can see an example here: https://noderun.com/alex/multiple-queries.

But please keep in mind that this may not work with all setups. Certain setups on IBM i, for example, may not allow multiple queries per session.

3 Likes

@Alex Thanks for the swift reply. I will check this and let you know in detail.

By the way, there is now a simple API available that simplifies all of this. It’s called pjs.parallelQueries().

https://docs.profoundlogic.com/x/6gAyAw

1 Like