Ajax API 循环调用需要按顺序执行

Ajax API calls in loop need to be executed in order

假设您有一个场景需要在页面的文本区域中创建 .csv 输出...

所以我有一组循环查询。在循环内,我将查询传递给 ajax 调用...我需要将 ajax 调用的结果附加到文本区域中。

我的问题是如何按照请求的顺序打印出结果(基本上是查询数组中的顺序)

//example array to loop.
var queries= ['query1', 'query', 'query3', 'query4'];

//the textarea where im going to print the results in order later to open in excel as a .csv file
var $csvText= $('#some-text-area');

//inserting the csv headers
$csvText.val('Column1, Column2\r\n');

$.each(queries, function(index, value){
   //someGoogleAPI is an ajax call from google's api
   someGoogleAPI(value).then(function(response){
      //Adding row with values
      $csvText.val(response.column1 + ',' response.column2 + '\r\n');
   });
})

这是一个简化的示例,但通过解决这个问题,我将了解如何解决我的问题。

谢谢大家。

您可以使用 reduce 代替 $.each 来创建任意的承诺列表。

queries.reduce(function(seq, val) {
    return seq.then(function() {
      return someGoogleAPI(val)
    })
    .then(function(response){
        var curr = $csvText.val();
        $csvText.val(curr + ',' + response.column1 + ',' + response.column2 + '\r\n');
      });
}, Promise.resolve());

jsfiddle: https://jsfiddle.net/75sse6n2/

看来您的查询并不相互依赖,因此可以并行执行。如果是这种情况,那么您真的只需要按顺序处理响应即可。您可以通过多种方式做到这一点:

运行 与 Promise.all()

并行

并行启动所有请求,收集所有结果,使用 Promise.all() 知道它们何时完成,然后插入所有结果。

//example array to loop.
var queries= ['query1', 'query', 'query3', 'query4'];

//the textarea where im going to print the results in order later to open in excel as a .csv file
var $csvText= $('#some-text-area');

//inserting the csv headers
$csvText.val('Column1, Column2\r\n');

Promise.all(queries.map(function(item) {
   return someGoogleAPI(value);
})).then(function(results) {
   $csvText.append(results.map(function(item) {
        return response.column1 + ',' response.column2;
   }).join('\r\n'));       
});

Promise.all() 将按顺序收集结果,无论哪个请求实际先完成。

对操作进行排序

您可以对您的操作进行排序,这样一次只有一个 运行,它的结果被插入,然后下一个是 运行 等等。这将是一个较慢的端到端 运行 时间,但可以中间显示结果。

//example array to loop.
var queries= ['query1', 'query', 'query3', 'query4'];

//the textarea where im going to print the results in order later to open in excel as a .csv file
var $csvText= $('#some-text-area');

//inserting the csv headers
$csvText.val('Column1, Column2\r\n');

queries.reduce(function(p, item) {
    return p.then(function() {
        return someGoogleAPI(item).then(function(result) {
            $csvText.append(result.column1 + ',' result.column2 + '\r\n');
        });
    });
}, Promise.resolve());

这将创建一系列链式承诺,这些承诺将按顺序执行,一个接一个,每个承诺在结果到达时插入。