Home > Software design >  Run multiple Javascript async calls in parallel without using self-executing functions (IIFE)
Run multiple Javascript async calls in parallel without using self-executing functions (IIFE)

Time:11-12

My code has to call a few web services. To speed that up, I want to do that in parallel. However, the results of those services must be executed before Promise.all() resolves. Here's my current code:

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

As you can see, I'm using a self-executing javascript function there. That doesn't really contribute to the readability of my code. Is there a better way to implement that without losing the ability to execute both calls in parallel?

CodePudding user response:

In general, aim achieve this type of thing by returning values instead of depending on side effects (i.e. assigning values to variables in the wider scope).

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

or, more concisely:

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

CodePudding user response:

const awaitors = [];

if (!targetLocation) {
    awaitors.push(getStorageLocation(storageID).then(targetLocation => {
        // process targetLocation 
    }));
}

if (!carrierToMove) {
    awaitors.push(/* do the same as above */);
}

// by the time this resolves, individual
// requests will be processed:
await Promise.all(awaitors); 

pushCarrierIntoStorage(carrierToMove, targetLocation);
  • Related