jQuery Recursive AJAX Call Promise

后端 未结 2 731
有刺的猬
有刺的猬 2020-12-06 02:11

I\'m still trying to figure out how to use jQuery deferred object in recursive AJAX call. I have a code like this

function request(page, items){    

    //b         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 02:53

    You should not use the success parameter if you want to work with promises. Instead, you want to return a promise, and you want to use then to transform the results of a promise into something different, possibly even another promise.

    function request(page) {    
        …
        // return the AJAX promise
        return $.ajax({
            url: '/echo/json/',
            method: 'POST',
            dataType: 'json',
            data: {
                delay: 1,
                json: JSON.stringify(ret)
            }
        });
    }
    
    function requestOddsFrom(page, items) {
        return request(page).then(function(data){
            if (data.currentPage > data.totalPage) {
                return items;
            } else {
                var filtered = data.items.filter(function(el){ return el%2 == 1; });
                return requestOddsFrom(data.currentPage + 1, items.concat(filtered));
            }
        });
    }
    
    function requestAll(){
        return requestOddsFrom(1, []);
    }
    
    requestAll().then(function(items) {
        console.dir(items);
    });
    

提交回复
热议问题