node.jscloudant

How to parallel execution of cloudant queries in Node js


I am trying to execute two queries in parallel. Here I'm able to execute one query and getting the results as well.

doGet : async (request, response) => {
    var usersState = [];
    var names = { "usersState": usersState, "message": "ok" };
    const queryForCricket = CloudantV1.Selector = {
       "hoby": "Cricket"
   };
   const queryForChess = CloudantV1.Selector = {
    "hoby": "Chess"
  };
  var query1 = {
    db: dbName,
    selector: queryForCricket,
    fields: ["_id", "name", "hoby" ],
    limit: 50,
    skip: 0
  };
  var query2 = {
    db: dbName,
    selector: queryForChess,
    fields: ["_id", "name", "hoby" ],
    limit: 50,
    skip: 0
  };
  service.postFind(query1).then(data => {
  data.result.docs.forEach(function (doc) {
  if(doc) usersState.push(doc);
  }
  response.send(names);
  });
  }

I tried to execute second query in parallel but it's not working as expected. For following snippet getting error like 'ERROR: unhandled rejection: TypeError: fn is not a function'. And I'm not sure that is correct approach or not.

async.parallel(
    [
       service.postFind(query1),
       service.postFind(query2),
     ], function (err, results) {
     if (err) {
    response.send({ "message": "Get operration failed" });
    return;
    } else {
    results.forEach(function (body) {
             body[0].docs.forEach(function (doc) {
                if (doc) usersState.push(doc);
            });
        });
         response.json(names);
    }
 );


Solution

  • I see you're using an async function, so it's easier to use the async/await syntax:

    // in series
    const res1 = await service.postFind(query1)
    const res2 = await service.postFind(query2)
    

    or

    // in parallel
    const results = await Promise.all([
      service.postFind(query1),
      service.postFind(query2)
    ])
    

    See Promise.all.