【问题标题】:JavaScript retrieve asynchronous data from an arrayJavaScript 从数组中检索异步数据
【发布时间】: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


【解决方案1】:

试试这样的

var mylist = [], dataArray = new Array(mylist.length), callCount = 0, callbackCounts = 0;
function getAsyncData(request, index, callback) {
    $.ajax({
        async: true,
        type: 'GET',
        url: request.url,
        index: index,
        success: function (aData) {
            let obj = {
                name: myList[index].name,
                data: aData.property
            };
            dataArray[index] = obj;
            callback();
        },
        error: function () {
            console.log('error for ' + myList[index].name);
            callback();
        }
    });
}
function allDataLoaded() {
    //all data loaded
}
myList.forEach(function (listItem, idx) {
    var found = dataArray.some(function (el) {
        return el.name === listItem.name;
    });
    if (!found) {
        callCount++;
        getAsyncData(listItem, idx, function () {
            callbackCounts++;
            if (callbackCounts === callCount) {
                allDataLoaded();
            }
        });
    }
});

【讨论】:

  • 谢谢,这给了我一个初步的想法,但这里的问题是没有固定数量的 callBackcounts。请求列表的长度可以是 10,其中 10 个可以是不同的请求,也可以是所有 10 个相同的请求。
  • 谢谢,我实现了这个并且效果很好,但我可能仍然更愿意使用基于承诺的结构,因为不做所有的加载 pre=过程感觉更好一些。感谢您的帮助,尽管在我弄清楚如何做替代结构之前这将完美地工作!
猜你喜欢
  • 2016-02-16
  • 1970-01-01
  • 2015-07-02
  • 2017-01-11
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多