[英]is it possible an iteration with asynchronous methods in javascript
I have a JSP with a Struts 2 include: 我有一个带有Struts 2的JSP,包括:
<div id="data">
<s:include value="list.jsp"/>
</div>
list.jsp has an iterator inside. list.jsp内部有一个迭代器。
With JavaScript I have 3 functions that make an Ajax call to different actions and web services but the 3 functions refresh the same Java object list: 使用JavaScript,我有3个函数可以对不同的动作和Web服务进行Ajax调用,但是3个函数可以刷新相同的Java对象列表:
function firstCall(product) {
// an ajax call
.done(function(html) {
$("#data").append(html);
});
}
function secondCall(product) {
// an ajax call
.done(function(html) {
$("#data").append(html);
});
}
function thirdCall(product) {
// an ajax call
.done(function(html) {
$("#data").append(html);
});
}
And i have another function that iterate a string array of products: 而且我还有另一个函数可以迭代产品的字符串数组:
function iterate(productos){
for(i=0;i<productos.length;i++){
firstCall(productos[i]);
secondCall(productos[i]);
thirdCall(productos[i]);
}
}
My problem is that I need these three methods to be asynchronous because each takes like 10 seconds. 我的问题是我需要这三种方法是异步的,因为每种方法都需要10秒钟。 =(
=(
There is a better way to do this? 有更好的方法吗?
If you do NOT care about older browsers (who doesn't support ES6) you can use promises. 如果您不关心较旧的浏览器(不支持ES6),则可以使用promises。 It would become
它会变成
new Promise(firstCall(productos[i]));
new Promise(seccondCall(productos[i]));
new Promise(thirdCall(productos[i]));
//You can add .then(function(){"code"}) to do something after it's done.
And your methods should have two new parameters: resolve and reject, that are functions that resolve or reject the promise. 而且您的方法应具有两个新参数:解析和拒绝,即解析或拒绝承诺的函数。 So .then works.
因此,那么工作。
If you care about older browsers you can use another implementation https://www.promisejs.org/ or see is there a way to implement promises in ie9+ 如果您关心较旧的浏览器,则可以使用另一种实现https://www.promisejs.org/,或者可以在ie9 +中实现诺言
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise for reference
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise以获取参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.