本文介绍了Promise.all()执行中能否将诺言的返回用作下一个函数调用的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究StackOverflow,还没有看到我所问问题的任何直接示例.我正在阅读有关备忘录的文章如果要查看,请链接此处.

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.

在我看来,您应该能够一起运行它们,并使用getSoupRecipe()的返回值作为hiroSoupChef()的输入

It appears to me that you should be able to run them all together and use the return value from getSoupRecipe() as input for hireSoupChef()

async function makeSoupFromType(soupType) {
    
    let [ soupRecipe, soupPan, soupChef ] = await Promise.all([
        
        getSoupRecipe(soupType),
        buySoupPan(),
        hireSoupChef(soupRecipe.requiredSkills)
    ]);
    
    return await makeSoup(soupChef, soupRecipe, soupPan);
}

所以问题是所有三个异步函数是否可以同时运行,并且一次 getSoupRecipe返回我使用它的变量名( 这是soupRecipe )作为hiringSoupChef的输入.

So the question is can all three async functions run at the same time and once getSoupRecipe returns I use it's variable name (which is soupRecipe) as input for hireSoupChef.

我将在此处发布所有其他代码,以供您查看,但我认为这可能会使问题看起来过于艰巨,因此上面的链接.您不必一定去看它就可以理解我的想法,因为我认为我已经说了正确的问题,但是如果您愿意的话.

推荐答案

不是靠它自己,不是.在您的示例中, soupRecipe (和其他两个变量)仅在 Promise.all(...) await 已被初始化后才初始化,因此它不能在作为参数传递给 Promise.all 的表达式中使用.毫无疑问, Promise.all 不是语法的一部分,实际上只是返回一个用数组一次来实现的promise.

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:

async function makeSoupFromType(soupType) {
    const soupRecipePromise = getSoupRecipe(soupType);
    const [soupRecipe, soupPan, soupChef] = await Promise.all([
        soupRecipePromise,
        buySoupPan(),
        soupRecipePromise.then(({requiredSkills}) => hireSoupChef(requiredSkills))
    ]);
    
    return makeSoup(soupChef, soupRecipe, soupPan);
}

或者,使用普通的 async / await ,您还可以使用IIFE避免 then()调用:

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

async function makeSoupFromType(soupType) {
    const [soupPan, [soupRecipe, soupChef]] = await Promise.all([
        buySoupPan(),
        (async () => {
            const soupRecipe = await getSoupRecipe(soupType);
            const soupChef = await hireSoupChef(soupRecipe.requiredSkills);
            return [soupRecipe, soupChef];
        })(),
    ]);
    
    return makeSoup(soupChef, soupRecipe, soupPan);
}

这篇关于Promise.all()执行中能否将诺言的返回用作下一个函数调用的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:01