【问题标题】:Run multiple Javascript async calls in parallel without using self-executing functions (IIFE)在不使用自执行函数 (IIFE) 的情况下并行运行多个 Javascript 异步调用
【发布时间】:2022-11-12 18:57:28
【问题描述】:

我的代码必须调用一些网络服务。为了加快速度,我想并行执行。但是,必须执行这些服务的结果前Promise.all() 解决。这是我当前的代码:

const awaitors = [];

if (!targetLocation) {
    awaitors.push((async function () {
        targetLocation = await getStorageLocation(storageID);
    })());
}

if (!carrierToMove) {
    awaitors.push(/* Another similar call that sets carrierToMove */);
}

await Promise.all(awaitors);
pushCarrierIntoStorage(carrierToMove, targetLocation);

如您所见,我在那里使用了一个自动执行的javascript函数。这对我的代码的可读性并没有真正的贡献。有没有更好的方法来实现它而不会失去并行执行两个调用的能力?

【问题讨论】:

    标签: javascript asynchronous async-await promise iife


    【解决方案1】:

    一般来说,目标是通过返回值而不是依赖于副作用来实现这种类型的事情(即将值分配给更广泛范围内的变量)。

    const promiseTargetLocation = getStorageLocation(storageID);
    const promiseCarrierToMove = anotherSimilarCall();
    const [carrierToMove, targetLocation] = await Promise.all([promiseCarrierToMove, promiseTargetLocation];
    pushCarrierIntoStorage(carrierToMove, targetLocation);
    

    或者,更简洁地说:

    pushCarrierIntoStorage(...(await Promise.all([anotherSimilarCall(), getStorageLocation(storageID)])));
    

    【讨论】:

    • 我的应用程序中的问题是,这两个变量可以已经由以前的代码定义。
    • 然后在提出更换请求之前对此进行测试。例如const promiseTargetLocation = existingLocation ?? getStorageLocation(storageID);
    猜你喜欢
    • 2020-11-14
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2015-12-26
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多