如何在 Node js 中并行执行 cloudant 查询

How to parallel execution of cloudant queries in Node js

我正在尝试并行执行两个查询。在这里,我能够执行一个查询并获得结果。

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);
  });
  }

我尝试并行执行第二个查询,但它没有按预期工作。对于以下代码段,出现 'ERROR: unhandled rejection: TypeError: fn is not a function' 之类的错误。我不确定这是否正确。

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);
    }
 );

我看到您正在使用 async 函数,因此使用 async/await 语法更容易:

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

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

Promise.all