Return an Array from an Async call, then additional Async calls for each element of the array

时光总嘲笑我的痴心妄想 提交于 2019-12-12 00:43:33

问题


I'm writing an application in javascript where I make a CORS request to the server to grab a data array.

Then, for each item in the array, I need to make another CORS call to get additional info on that element.

I originally thought I could return values from my CORS request like:

data = getData(param);

But apparently you can't mix synchronous and asynchronous code.

What's the best way to accomplish this?


回答1:


Promises. Here's how you might use them using your requirements, and a setTimeout to mimic an AJAX request.

getData returns a new promise. In this case if the function is called with no params an array is sent back after a second (your first request). If a param is passed into the function 100 is added to the param before resolving - the later requests.

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

Call getData without a param and [1, 2, 3, 4, 5] is returned. then we map over the array elements and return new promises for each of them. then we use Promise.all to resolve those promises and then we output the final array [101, 102, 103, 104, 105].

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

DEMO

So you can see that you can run one AJAX request and then run more based on the result of the value that's returned until all requests have been made.




回答2:


You can use async.series. checkout https://github.com/caolan/async . Very good library to solve problem like this - process an array data asynchronously(My favourite).

Or

You can use js promise from https://www.promisejs.org/

Or play with callbacks... like below

Note: Below functions are indicative functions just to show how you can approach the problem as you haven't shared any code. Change them accordingly. Also there might be syntactical/spell error as the code is written directly here.

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
 }
} 


来源:https://stackoverflow.com/questions/36776114/return-an-array-from-an-async-call-then-additional-async-calls-for-each-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!