2016-04-21 156 views
0

我正在写一个应用程序在JavaScript中,我向服务器发出CORS请求以获取数据数组。从异步调用返回一个数组,然后额外的异步调用数组中的每个元素

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

我本来以为从我CORS要求像我可以返回值:

data = getData(param); 

但很显然,你不能混用同步和异步代码。

完成此操作的最佳方法是什么?

+0

您能否展示一个更完整的代码示例,演示如何尝试“混合同步和异步代码”? –

回答

1

承诺。您可以按照您的要求使用它们,并使用setTimeout来模仿AJAX请求。

getData返回新的承诺。在这种情况下,如果调用没有参数的函数,则在第二次(第一次请求)之后发回一个数组。如果一个参数被传入函数100在解析之前被添加到参数 - 稍后的请求。

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没有PARAM和[1, 2, 3, 4, 5]返回。 then我们映射数组元素并返回新的对他们每个人的承诺。 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请求,然后根据直到所有请求已作出所返回的值的结果运行更多。

0

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

或者

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

或者有回调玩JS承诺......像下面

注:以下功能指示功能只是为了展示如何您可以解决问题,因为您没有共享任何代码。相应地更改它们。也可能会出现语法/拼写错误,因为代码直接写入此处。

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