简体   繁体   English

将 Promise.All 用于多个 ajax 请求时,如何将该数据分配给局部变量?

[英]When using Promise.All for multiple ajax requests, how do I assign that data to a local variable?

I am trying to use Promise.All() three times.我试图使用 Promise.All() 三次。 Each one for a specific array of ajax requests that call a function in my code-behind that returns a jsonresult.每个都用于特定的 ajax 请求数组,这些请求在我的代码隐藏中调用一个函数,返回一个 jsonresult。 Is there a way I can get the array return from promise.all and assign it to local array.有没有办法可以从 promise.all 获取数组返回并将其分配给本地数组。 I originally tried using async:false on ajax but it is incredibly slow.我最初尝试在 ajax 上使用 async:false 但它非常慢。 Are there any other possibilities?还有其他可能吗?

You're in luck!你很幸运! Promise.all returns an array, with each element in the output corresponding to the elements of the input. Promise.all返回一个数组,输出中的每个元素对应于输入的元素。

let asyncResults = await Promise.all([
    asyncOp0(),
    asyncOp1(),
    asyncOp2()
])

At this point, asyncResults is a local array.此时, asyncResults是一个本地数组。

asyncResults[0] will be the return of asyncOp0 asyncResults[0]将是 asyncOp0 的返回值

asyncResults[1] will be the return of asyncOp1 asyncResults[1]将是 asyncOp1 的返回值

asyncResults[2] will be the return of asyncOp2 asyncResults[2]将是 asyncOp2 的返回值

It sounds like that's exactly what you want.听起来这正是你想要的。

If it's not returning fast enough for you, the likely culprit is the HTTP endpoint you're hitting.如果它对您来说返回的速度不够快,则可能的罪魁祸首是您正在访问的 HTTP 端点。 You should study the performance of that endpoint.您应该研究该端点的性能。 Alternatively, if the HTTP response is very large, bad performance is just a consequence of that.或者,如果 HTTP 响应非常大,则性能不佳只是其结果。 The remedy might require you to redesign the server API to return a smaller representation of the data you care about.补救措施可能需要您重新设计服务器 API,以返回您关心的数据的较小表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM