【发布时间】:2018-03-19 13:10:45
【问题描述】:
编辑除了以下概念性的一种方式外,还添加了实际代码。 以下是我尝试实现异步数组访问的结构。
for (p = 0; p < myList.length ; p++){
for (k = 0; k < RequestList.length; k++){
if (RequestList[k].name === myList[p].name){
data = RequestList[k].data;
//process data
return //only intention is to exit if made use of the stored data
}
}
// if mylist.name is not in the Requestlist
// make the async request for it then push to RequestList array
// so the next time this name instance appears we use the previous data
$.ajax({
async: true,
type: 'GET',
url: url,
index: p,
success: function(aData) {
let obj = {
name : myList[index].name,
data = aData.property //....
}
RequestList.push(obj);
//process data
}
}
这里是概念解释
var dataArray = []
for loop
第一次循环迭代
value = 5
dogdata = //ajax api request to dog
//attempt to store this data for later use
dataArray[1].name = "dog"
dataArray[1].data = //async request fills this index with dog data
//process dogdata with value 5
第二次循环迭代
value = 3
catdata = //ajax api request to cat
//need data for cat and there are no cat named objects in the dataArray so
dataArray[2].name = "cat"
dataArray[2].data = //async request fills this index with cat data
//process catdata with value 3
第三次循环迭代
value = 8
//need data for dog but there is an object named dog at dataArray[1]
//so reach out to that instead of a new request
dogdata = dataArray[1].data // empty
//process dog data with value 8 this time!
显然 dogdata 最终为空,因为第一次异步调用尚未成功
所以当 dataArray[1] 的请求成功时,我希望通过该请求响应来处理这个问题,而不是阻塞整个循环
可能在此处回调第一个请求的成功或此处的 promise resolve 可能很有用。
第四次循环迭代
//need data for monkey and there are no monkey named objects in the array so
dataArray[3].name = "monkey"
dataArray[3].data = //async request fills this with monkey data
//.... goes on like this for many iterations
【问题讨论】:
-
您需要提供更多实际代码。这个问题在这一点上太抽象了,无法回答,因为有很多方法可以实现异步,而且答案会非常不同。
-
感谢您的回答!希望这能让它更清楚。
-
听起来你需要使用一个承诺。这将允许您发出单独的 ajax 请求并执行一些功能而不会阻塞。
-
在制定解决方案之前需要查看更多代码
标签: javascript ajax asynchronous callback promise