在序列的多Ajax请求使用递归函数并执行回调函数的所有请求完成后,递归、函数、序列、回调

2023-09-10 17:08:06 作者:笑我活该

我的名字用逗号分隔的列表。我想是我想呼吁在一个阵列内的序列,结果存储的所有名称服务器的请求。我试着和它的工作时,我也有不同的名里有一串数字。

I have list of names separated by comma. What I want is I want to call server request for all names in a sequence and store result inside an array. I tried and it's working when I do have number of names which are there in string.

请参阅这里 - 当我知道名字的数量这是工作

See Here - This is working when I know number of names

现在我要的是我想使这个code为一般。如果我在那个字符串添加一个名称,它会自动处理,不添加任何code为Ajax请求。

Now what I want is I want to make this code as generic. If I add one name in that string, It should handle automatically without adding any code for ajax request.

请参阅这里 - 这是我试过。它不是按预期工作。

See Here - This is what I've tried. It's not working as expected.

shoppingList = shoppingList.split(",");
var result = [];

function fetchData(shoppingItem)
{
    var s1 = $.ajax('/items/'+shoppingItem);
    s1.then(function(res) {
        result.push(new Item(res.label,res.price));
        console.log("works fine");
    });
    if(shoppingList.length == 0)
    {
        completeCallback(result);
    }
    else
    {
        fetchData(shoppingList.splice(0,1)[0]);
    }
}

fetchData(shoppingList.splice(0,1)[0]);

问题

我没有得到如何检测,所有的承诺目标已经得到解决,这样我可以调用回调函数。

I am not getting how to detect that all promise object have been resolved so that I can call callback function.

推荐答案

为了让序列中的Ajax请求,你必须把在回调递归调用:

To make the ajax requests in sequence, you have to put the recursive call in the callback:

function fetchList(shoppingList, completeCallback) {
    var result = [];
    function fetchData() {
        if (shoppingList.length == 0) {
            completeCallback(result);
        } else {
            $.ajax('/items/'+shoppingList.shift()).then(function(res) {
                result.push(new Item(res.label,res.price));
                console.log("works fine");
                fetchData();
//              ^^^^^^^^^^^
            });
        }
    }
    fetchData();
}

或你实际使用的承诺,做

or you actually use promises and do

function fetchList(shoppingList) {
    return shoppingList.reduce(function(resultPromise, shoppingItem) {
        return resultPromise.then(function(result) {
            return $.ajax('/items/'+shoppingItem).then(function(res) {
                result.push(new Item(res.label,res.price));
                return result;
            });
        });
    }, $.when([]));
}

(更新的jsfiddle )

的通知中没有任何关于Ajax请求的任务的要求,按顺序进行。你也可以让他们在并行和等待他们全部完成:

Notice there is nothing in the requirements of the task about the ajax requests to be made sequentially. You could also let them run in parallel and wait for all of them to finish:

function fetchList(shoppingList) {
    $.when.apply($, shoppingList.map(function(shoppingItem) {
        return $.ajax('/items/'+shoppingItem).then(function(res) {
            return new Item(res.label,res.price);
        });
    })).then(function() {
        return Array.prototype.slice.call(arguments);
    })
}

(更新的jsfiddle )