本文介绍了我想将数组变量作为参数传递时如何使用Promise.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在使用Promise.all()时遇到问题。 我想将数组变量作为参数传递给Promise.all(),例如 const promArr = [] if(condition1){ promArr.push(() => prom1(arg1,arg2))} if(condition2){ promArr.push(()=> prom2(arg1,arg2))} if(promArr.length> 0)Promise.all(promArr) 但是上面没有即使条件满足,也不要运行promise函数( prom1 , prom2 )。 ( promArr.length 符合我的预期) 如果我直接将promise函数推到 promArr ,恐怕它们当时被推送到 promArr ,而不是 Promise.all(promArr )。 在这种情况下如何正确使用Promise?解决方案使用 promArr 变量就可以了。但是,(顾名思义)它应该是一个Promise数组,而不是返回Promise的函数数组。 const promArr = [] if(condition1){ promArr.push(prom1(arg1,arg2))} if(condition2){ promArr.push( prom2(arg1,arg2))} 返回Promise.all(promArr) 如果我直接将promise函数推入 promArr ,恐怕它们当时正在运行,并被推到 promArr ,而不是 Promise.all(promArr)。 Promise.all 不会运行任何功能,您必须自己执行。是的,通过立即在条件块内调用 prom1 和 prom2 ,它们将在条件评估后立即开始,但是如果它们是适当异步的,并且不干扰以下条件,那么这不是问题。请注意,尚未等待他们返回的承诺,它们将并行处理。 I'm in a problem using Promise.all().I'd like to pass an array variable as an argument to Promise.all() like below.const promArr = []if (condition1) { promArr.push(() => prom1(arg1, arg2))}if (condition2) { promArr.push(() => prom2(arg1, arg2))}if (promArr.length > 0) Promise.all(promArr)But above doesn't run the promise functions(prom1, prom2) even if conditions are all true. (promArr.length is as I expected)if I push promise functions directly to promArr, I'm afraid they run at that time they are pushed to promArr, not at Promise.all(promArr).How can I use Promise properly in this case? 解决方案 Using a promArr variable is just fine. However (as the name suggests), it should be an array of promises, not an array of functions that return promises.const promArr = []if (condition1) { promArr.push(prom1(arg1, arg2))}if (condition2) { promArr.push(prom2(arg1, arg2))}return Promise.all(promArr) if I push promise functions directly to promArr, I'm afraid they run at that time they are pushed to promArr, not at Promise.all(promArr).Promise.all won't run any functions, you have to do it yourself. Yes, by calling prom1 and prom2 immediately inside the conditional block, they will start right after the condition is evaluated, but if they're properly asynchronous and don't interfere with the following conditions that is not a problem. Notice that the promises they return are not awaited yet, they'll do their processing in parallel. 这篇关于我想将数组变量作为参数传递时如何使用Promise.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 09:45