Chain ajax and execute it in sequence. Jquery Deferred

后端 未结 5 630
旧时难觅i
旧时难觅i 2020-11-30 02:53

I have 3 processes that needs ajax to complete. But it is asynchronous and it fails to do what I wanted to do..

Lets say:

function a(param1, param2)         


        
5条回答
  •  Happy的楠姐
    2020-11-30 03:17

    You can chain asynchronous calls like ajax calls using jQuery's deferred object and using 'then'.

    You can also change it to use functions that returns a deferred promise object, instead of an ajax call as I have in my example.

    http://jsfiddle.net/q4cFv/

    (Example with async function: http://jsfiddle.net/q4cFv/1/)

    $(function() {
        var delay = 3,
            span = $('span'),
            posts = [
                {
                    input1: 'My name 1',
                    input2: 'My address 1',
                    input3: 'My country 1'
                },
                {
                    input1: 'My name 2',
                    input2: 'My address 2',
                    input3: 'My country 2'
                },
                {
                    input1: 'My name 3',
                    input2: 'My address 3',
                    input3: 'My country 3'
                },
                {
                    input1: 'My name 4',
                    input2: 'My address 4',
                    input3: 'My country 4'
                }
            ],
            looper = $.Deferred().resolve();
    
        $.each(posts, function(i, data) {
            looper = looper.then(function() {
                return $.ajax({
                    data: {
                        json: JSON.stringify(data),
                        delay: delay
                    },
                    method: 'post',
                    url: '/echo/json/',
                    dataType: 'json'
                }).done(function(response) {
                    span.append('Response:
    '); for(key in response) { span.append(key + ': ' + response[key] + '
    '); } $('span').append('Waiting ' + delay + ' seconds

    '); }); }); }); });

提交回复
热议问题