是否有可能在 JavaScript 中使用异步方法进行迭代

is it possible an iteration with asynchronous methods in javascript

本文关键字:异步方法 迭代 有可能 JavaScript 是否      更新时间:2023-09-26

我有一个带有Struts 2的JSP包括:

<div id="data">
  <s:include value="list.jsp"/>
</div>

list.jsp 里面有一个迭代器。

使用 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);
    });
}

我还有另一个函数可以迭代一串产品数组:

function iterate(productos){
    for(i=0;i<productos.length;i++){
        firstCall(productos[i]);
        secondCall(productos[i]);
        thirdCall(productos[i]);
    }
}

我的问题是我需要这三个方法是异步的,因为每个方法需要 10 秒。 =(

有更好的方法吗?

如果你不关心旧的浏览器(不支持ES6),你可以使用promises。它会变成

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.

你的方法应该有两个新参数:solve和reject,它们是解析或拒绝承诺的函数。所以.then工作。

如果您关心较旧的浏览器,您可以使用其他实现 https://www.promisejs.org/或查看是否有办法在 ie9+ 中实现承诺

请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 以供参考