Skip to content Skip to sidebar Skip to footer

Can The Return Of A Promise Be Used As An Input For The Next Function Call In A Promise.all() Execution?

I've been looked on StackOverflow and haven't seen any direct examples of what I'm asking. I'm reading this article on memoization link here if you want to look. It appears to me t

Solution 1:

Not by itself, no. In your example the soupRecipe (and the other two variables) are only initialised after the Promise.all(…) has been awaited, so it can't be used in the expressions that are passed to Promise.all as an argument. There's no magic going on here, Promise.all is not part of the syntax but really just returning one promise that fulfills with an array once.

However, the approach outlined in this answer to How do I access previous promise results in a .then() chain? does enable the desired chaining of asynchronous actions:

asyncfunctionmakeSoupFromType(soupType) {
    const soupRecipePromise = getSoupRecipe(soupType);
    const [soupRecipe, soupPan, soupChef] = awaitPromise.all([
        soupRecipePromise,
        buySoupPan(),
        soupRecipePromise.then(({requiredSkills}) =>hireSoupChef(requiredSkills))
    ]);
    
    returnmakeSoup(soupChef, soupRecipe, soupPan);
}

Alternatively, with plain async/await you could also use an IIFE to avoid the then() call:

asyncfunctionmakeSoupFromType(soupType) {
    const [soupPan, [soupRecipe, soupChef]] = awaitPromise.all([
        buySoupPan(),
        (async () => {
            const soupRecipe = awaitgetSoupRecipe(soupType);
            const soupChef = awaithireSoupChef(soupRecipe.requiredSkills);
            return [soupRecipe, soupChef];
        })(),
    ]);
    
    returnmakeSoup(soupChef, soupRecipe, soupPan);
}

Post a Comment for "Can The Return Of A Promise Be Used As An Input For The Next Function Call In A Promise.all() Execution?"