Home>

There are multiple functions that get values ​​in AJAX.

I want to execute these asynchronously and in parallel with JavaScript and jQuery, and process the results sequentially.

Corresponding source code

In the following source code

func1 ()
func2 ()

While running in parallel

console.log (respose1);
console.log (respose2);

Means that I want to process each as soon as the acquisition is completed.

(That is,func1 ()As soon as the acquisition is completedconsole.log (respose1);I want to process. )

$(function () {
    $.when (
        func1 (),
        func2 ()
    ) .done (function (respose1, respose2) {
        console.log (respose1);
        console.log (respose2);
    }) .fail (function () {
        console.log ('error');
    });
    function func1 () {
        const def = $.Deferred ();
        $.ajax ({{
            url:'http://example.com/ajax',
            type:'POST',
            data: {id: 1}
        }) .done (function (response1) {
            def.resolve (response1);
        });
        return def.promise ();
    }
    function func2 () {
        const def = $.Deferred ();
        $.ajax ({{
            url:'http://example.com/ajax',
            type:'POST',
            data: {id: 2}
        }) .done (function (response2) {
            def.resolve (response2);
        });
        return def.promise ();
    }
});
What I tried

$.when.applyI tried using, but I couldn't do it sequentially.

const functions = [func1 (), func2 ()];
$.when.apply (null, functions) .then (
    function (... responses) {
        responses.forEach (function (response, i) {
            console.log (respose);
        });
    }
});


If there is a good way, thank you.

  • Answer # 1

    const func1 = () =>new Promise (resolve =>setTimeout (() =>resolve (1), 3000));
    const func2 = () =>new Promise (resolve =>setTimeout (() =>resolve (2), 1000));
    const func3 = () =>new Promise (resolve =>setTimeout (() =>resolve (3), 2000));
    const wrap = async (func) =>console.log (await func ());
    console.log ("start");
    Promise.all ([[
      wrap (func1),
      wrap (func2),
      wrap (func3),
      ]) .then (res =>console.log ("end"));