JavaScript从数组中检索异步数据

时间:2017-10-08 04:43:20

标签: javascript ajax asynchronous callback promise

编辑除了以下概念之外,还添加了实际代码。 以下是我尝试实现异步数组访问的结构。

NAN

下面的概念解释

<script>
    $(function(){
        $("#currency-converter").keyup(function(){
            $('#label').text(parseFloat($("#currency-converter").text) + " BTC-ICO");
        });
    });
</script>

第一次循环迭代

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

显然dogdata最终是空的,因为第一次异步调用尚未成功

所以当dataArray [1]的请求成功时,我希望在不阻塞整个循环的情况下处理该请求响应

可能会回复第一次要求此处的成功,或者此处的承诺解决方案可能会有用。

第四次循环迭代

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

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

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