繁体   English   中英

如何用 Promise.all 替换多个 async/await 调用?

[英]How to replace multiple async/await calls with Promise.all?

我有以下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);
}

这里,

const firstData = 
{
  "total": 2,
  "rows": [
    {
      "hostname": "abc.com",
      "ipAddress": "11.11.11.11",
      "myservice1Id": "ee0f77c9-ef15",
      "type": "type1"
    },
    {
      "hostname": "cde.com",
      "ipAddress": "12.12.12.12",
      "type": "type2",
      "myservice1Id": null
    }
  ]
}   


const aRes = 
[
  {
        "listType": "list1",
        "createdAt": "2020-12-07"
  }
]


const oRes =
{
  "rows": [
    {
      "status": "FAIL"
    }
  ]
}


const vRes =
{
  "rows": [
    {
      "status": "FAIL"
    }
  ]
}

返回的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 blocks都可以并行执行,因为它们彼此独立。 我可以使用Promise.all parallel执行所有 3 个if blocks吗? 如果是,更新后的代码使用Promise.all看起来如何?

最简单的调整是将每个 Promise 推送到if 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);

您还可以通过只检查一次hostName来简化代码,看起来您正在迭代整个数组,这可以通过调用迭代器更轻松地完成:

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

现在这里的问题是你必须等到最慢的迭代完成,你可以使用 promise 池修复它, @supercharge/promise-pool

MDN Promise 中博客源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM