Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何用Promise.all替换多个异步/等待调用?_Javascript_Node.js_Json_Promise_Async Await - Fatal编程技术网

Javascript 如何用Promise.all替换多个异步/等待调用?

Javascript 如何用Promise.all替换多个异步/等待调用?,javascript,node.js,json,promise,async-await,Javascript,Node.js,Json,Promise,Async Await,我有下面的try/catch块,它正在进行3个不同的api调用。 下面的代码工作正常,但是当firstData具有较大的数据集时,执行它会花费很多时间 try { const firstData = await myservice1.myservice1Func(); for(let i=0; i<firstData.total; i++){ const hostName = firstData.rows[i]['hostname']; i

我有下面的
try/catch
块,它正在进行3个不同的api调用。 下面的代码工作正常,但是当
firstData
具有较大的数据集时,执行它会花费很多时间

try {
    const firstData = await myservice1.myservice1Func();

    for(let i=0; i<firstData.total; i++){
        const hostName = firstData.rows[i]['hostname'];
        if (hostName !== null && firstData.rows[i]['myservice1Id'] !== null) {
            const aRes = await myService2(hostName);
            firstData.rows[i]['mylist'] =
                    aRes[0].dataValues;
        }
        if (hostName !== null && firstData.rows[i]['type'].includes('type1')) {
            const oRes = await myService3(hostName);
            firstData.rows[i]['ores'] = oRes.rows[0];
        }
        if (hostName !== null && firstData.rows[i]['type'].includes('type2')) {
            const vRes = await myService4(hostName);
            firstData.rows[i]['vRes'] = vRes.rows[0];
        }
    }
    return firstData;
} catch (err) {
    console.log(err);
}
返回的
firstData
的最终值如下:

{
  "total": 2,
  "rows": [
    {
      "hostname": "abc.com",
      "ipAddress": "11.11.11.11",
      "myservice1Id": "ee0f77c9-ef15",
      "type": "type1",
      "oRes": {
        "status": "PASS"
      },
      "mylist": {
        "listType": "list1",
        "createdAt": "2020-12-07"
      }
    },
    {
      "hostname": "cde.com",
      "ipAddress": "12.12.12.12",
      "type": "type2",
      "myservice1Id": null,
      "vRes": {
        "status": "FAIL"
      }
    }
  ]
}   
这里需要注意的是,所有3个
if块都可以并行执行,因为它们彼此独立。
我可以使用
Promise.all
执行
并行
中的所有3个
if块吗?

如果是,则使用
Promise更新的代码会是什么样子。所有的

最简单的调整是将每个Promise推送到
中的一个数组,如果
s:

const proms = [];
if (hostName !== null && firstData.rows[i].myservice1Id !== null) {
    proms.push(
      myService2(hostName)
        .then(aRes => firstData.rows[i].mylist = aRes[0].dataValues)
    );
}
// other ifs changed around the same way

await Promise.all(proms);
您还可以通过只检查一次
主机名
来简化代码,而且看起来您正在对整个数组进行迭代,通过调用迭代器可以更轻松地完成:

try {
    const firstData = await myservice1.myservice1Func();
    for (const row of firstData.rows) {
        const hostName = row.hostname;
        if (hostName === null) continue;
        const proms = [];
        if (row.myservice1Id !== null) {
            proms.push(
                myService2(hostName)
                    .then(aRes => row.mylist = aRes[0].dataValues)
            );
        }
        // etc

嗨,你有一些代码修改

for(let i=0; i<firstData.total; i++){
    const hostName = firstData.rows[i]['hostname'];

     //check if condition inside the service and return a null (a promise)
     Promise.all([myService2(hostName), myService3(hostName), myService4(hostName)]).then((values) => {
        console.log(values);
        //[resutl1,null,result3]
     });
}
for(设i=0;i{
console.log(值);
//[结果1,空,结果3]
});
}
现在的问题是你必须等到最慢的迭代完成, 你可以用promise pool use解决这个问题,


能否建议将循环的
包含在何处?
与当前代码中的位置相同。有了答案中的代码,您最多可以提出3个并行请求,这是非常合理的,我通常不想超出这个范围,尽管这取决于服务可以处理的并行度?不,你只需要等待承诺如答案中所示,然后在该点之后,该行将被完全填充。我收到一个错误
TypeError:cannotread property'dataValues'of undefined
您能告诉我在哪里添加未定义的检查吗?
for(let i=0; i<firstData.total; i++){
    const hostName = firstData.rows[i]['hostname'];

     //check if condition inside the service and return a null (a promise)
     Promise.all([myService2(hostName), myService3(hostName), myService4(hostName)]).then((values) => {
        console.log(values);
        //[resutl1,null,result3]
     });
}