my first post here, hi everyone :)
i have this js code to access a json api:
function a() {
    //does some things
    //...
    //then calls function b
    b(some_params);
}
function b(params) {
    //calls an objects method that makes an ajax call to an api and get the response in json
    someObject.makeajaxcalltoapi(params, function(response) {
        alertFunction(response);
    });
}
function alertFunction(resp) {
    console.log ("the response is: ");
    console.log(resp);
}
this is working ok, but now i need to modify it in order to do this: in function a(), instead of making a single call to b(), i need to call b() multiple times in a loop, with different parameters each time. and then i want to call alertFunction() passing it an array with all the responses, but only after all responses have been received.
i have tried to use $.when and .then, after seeing some examples on deferred objects, but its not working:
function a() {
    //does some things
    //...
    //then calls function b
    var allResponses = [];
    $.when(
        anArray.forEach(function(element) {
            allResponses.push(b(some_params));
        });
    ).then(function() {
        alertFunction(allResponses);
    });
}
function b(params) {
    //calls an objects method that makes an ajax call to an api and get the response in json
    someObject.makeajaxcalltoapi(params, function(response) {
        //alertFunction(response);
    });
    return response;
}
function alertFunction(allresp) {
    console.log ("the responses are: ");
    console.log(allresp);
}
any help?
UPDATE - ok finally got it working. i put here the final code in case it helps somebody else...
function a() {
    //does some things
    //...
    //then calls function b
    var requests = [];
    //-- populate requests array
    anArray.forEach(function(element) {
        requests.push(b(some_params));
    });
    $.when.apply($, requests).then(function() {
        alertFunction(arguments);
    });
}
function b(params) {
    var def = $.Deferred();
    //calls an objects method that makes an ajax call to an api and get the response in json
    someObject.makeajaxcalltoapi(params, function(response) {
        def.resolve(response);
    });
    return def.promise();
}
function alertFunction(allresp) {
    console.log ("the responses are: ");
    console.log(allresp);
}
 
    