【问题标题】:Loop a function which includes an Ajax Call in Javascript循环包含 Javascript 中的 Ajax 调用的函数
【发布时间】:2019-12-07 00:02:38
【问题描述】:

test() 下面的函数将在循环内被loopTheTest() 调用 6 次。

我希望这 6 个调用同步运行。

我知道async:false 是一种不好的做法,我找不到关于如何实现这一点的明确解决方案。

我检查了主题 promisesasync-await,但无法将它们应用于以下情况(由于我缺乏知识)。

PS:我不是在寻找递归解决方案。

function loopTheTest(){

     var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

     for (i = 0; i < cars.length; i++) {
         test(cars[i]);
     }
}
function test(car){
    //Some Codes
    //AJAX POST REQUEST
    //Some Codes
}

【问题讨论】:

  • 更好的方法是在服务器端处理数组,只需要使用所有值调用它一次。否则,您始终可以通过将 false 作为第三个参数传递来使您的请求同步。 developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
  • Promise.all(cars.map(test)).then(function(arrayOfResults) { /* 对结果做一些事情 */ });

标签: javascript asynchronous promise async-await synchronous


【解决方案1】:

使用 async/await 并使用 jsonplaceholder 进行“真正的”fetch(),您可以通过 for/of 循环获得结果:

require('isomorphic-fetch');

const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
const url = "https://jsonplaceholder.typicode.com/albums/";

async function test(car,i){
    const result = await fetch(url+(i+1));
    const descr = await result.json();
    return cars[i] + " " + descr.title;
}

async function loopTheTest() {
    for (const [i, car] of cars.entries()) {
      let res = await test(car,i);
      console.log(`Received test ${i + 1}:`, res);
    }
    console.log(' Finish !!!');
  }

loopTheTest();

你得到:

Received test 1: BMW quidem molestiae enim
Received test 2: Volvo sunt qui excepturi placeat culpa
Received test 3: Saab omnis laborum odio
Received test 4: Ford non esse culpa molestiae omnis sed optio
Received test 5: Fiat eaque aut omnis a
Received test 6: Audi natus impedit quibusdam illo est
 Finish !

【讨论】:

  • 什么是同构提取? .你能在 jsfiddle 上实现上面的代码吗?我无法让它工作。
  • 以防万一您在 nodeJS(服务器端)中执行它。
  • 否则将 jsonplaceholder 替换为您的服务器 url 以避免 CORS 问题
  • 我试图实现你的代码,但我想我遗漏了一些东西。你能用我的真实代码检查我的另一个线程吗? stackoverflow.com/questions/59219048/…
【解决方案2】:

当你用ajax循环时,调用下一个ajax就成功了:

var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
cnt = 0;

function test() {
  if (cnt >= cars.length) return; // stop

  var car = cars[cnt];
  fetch("someprocess?car=" + car)
    .then(function(data) {
      showFunction(data);
      cnt++;
      test();
    })
}
test()

【讨论】:

  • 谢谢,但就我而言,我不是在寻找递归解决方案。我需要一个包括 for 循环的解决方案。我在发布到 stackoverflow 之前简化了我的代码。
  • 我希望我还那么年轻。 :)
【解决方案3】:

如果你想让它们按顺序运行,这样的东西应该可以工作

var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
async function test() {
    for (let index = 0; index < cars.length; index++) {
        const data = await fetch("someprocess?car=" + cars[index])
        // do whatever you want to do with the response data here
    }
}

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 2019-01-23
    • 2022-09-27
    • 2016-12-17
    • 2016-07-13
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多