从异步调用返回一个数组,然后为该数组的每个元素调用其他异步调用

时间:2016-04-21 16:59:50

标签: javascript asynchronous architecture synchronous

我正在用javascript编写一个应用程序,我向服务器发出一个CORS请求以获取数据数组。

然后,对于数组中的每个项目,我需要进行另一次CORS调用以获取有关该元素的其他信息。

我原本以为我可以从我的CORS请求返回值,如:

data = getData(param);

但显然你不能混合同步和异步代码。

实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

承诺。以下是使用您的要求使用它们的方法,以及setTimeout来模仿AJAX请求。

getData会返回新的承诺。在这种情况下,如果调用该函数时没有参数,则会在一秒钟后(第一次请求)发回一个数组。如果将一个param传递给函数100,则在解析之前将其添加到param中 - 后来的请求。

function getData(param) {
  return new Promise(function(resolve, reject) {
    if (param) {
      setTimeout(() => resolve(param + 100), 500);
    } else {
      setTimeout(() => resolve([1, 2, 3, 4, 5]), 1000)
    }
  });
}

在没有参数的情况下调用getData并返回[1, 2, 3, 4, 5]then我们映射数组元素并为每个元素返回 new promises。 then我们使用Promise.all来解决这些承诺,then我们输出最终数组[101, 102, 103, 104, 105]

getData()
  .then((arr) => arr.map(el => getData(el)))
  .then(arr => Promise.all(arr))
  .then(arr => console.log(arr));

DEMO

因此,您可以看到您可以运行一个AJAX请求,然后根据返回的值的结果运行更多,直到所有请求都已完成。

答案 1 :(得分:0)

您可以使用async.series。结帐https://github.com/caolan/async。非常好的库来解决这样的问题 - 异步处理数组数据(我最喜欢的)。

您可以使用https://www.promisejs.org/

中的js promise

使用回调播放...如下所示

注意:下面的功能是指示功能,只是为了说明如何处理问题,因为您还没有共享任何代码。相应地改变它们。也可能存在语法/拼写错误,因为代码直接写在这里。

function ajaxRequester(method,uri, data, onSuccess, onError){ // you can make this function as per requirement.
   $.ajax({
    type: method,
    url: uri,
    data: data
    success: function(response){
     onSuccess(response);
    }
   });
}
function yourFunction(){
 ajaxRequester('GET',urlOf1stRequest,dataToSend,function(resp){
    // assuming resp is the array received from server. we'll start with 0th element 
  processArray(0,resp, function(){
   // do your final stuff
  });
 });
}

function processArray(index, arr, onComplete){
 if(index < arr.lenght){
  var objToProcess = arr[index]; // get your data to process
  ajaxRequester(yourMethod,obj.url, obj.data, function(resp){
   // do work with your response variable resp
    processArray(++index, arr); // process next element of array after completion of current
  });

 } else {
  onComplete(); // all elements are processed call final callback
 }
}