![](/img/trans.png)
[英]call async function for each array element of a promise result object, make changes and return this object
[英]Return an Array from an Async call, then additional Async calls for each element of the array
我正在用javascript编写应用程序,向服务器发出CORS请求以获取数据数组。
然后,对于数组中的每个项目,我需要进行另一个CORS调用以获取有关该元素的其他信息。
我本来以为可以从CORS请求中返回值,例如:
data = getData(param);
但是显然您不能混合使用同步和异步代码。
做到这一点的最佳方法是什么?
承诺。 这是使用需求和setTimeout
模仿AJAX请求的方法。
getData
返回一个新的Promise。 在这种情况下,如果不带参数调用该函数,则在第二秒(您的第一个请求)之后将数组发回。 如果将参数传递给函数,则在解析之前将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
并返回[1, 2, 3, 4, 5]
。 then
我们映射到数组元素,并为每个元素返回新的 Promise。 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));
因此,您可以看到可以运行一个AJAX请求,然后根据返回值的结果运行更多AJAX请求,直到发出所有请求为止。
您可以使用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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.