0

How can i pass arguments to Sequence promises using q.promises

var argumentsArray = ["PARAM1", "PARAM2", "PARAM3"]
var arr = [];
function aJaxCall(argumentsArray) {
    var deferred = Q.defer();
    $.ajax({
        type: 'POST',
        /*
            Here i want to get the passed parameter and use it
            in my post request
        */
        url: 'someurl.com' + PARAMS,
        // data: data,
        dataType: 'text',
        success: function (data) {
            arr.push(data);
            deferred.resolve(data);
        }
    });
    return deferred.promise;
}

var result = Q();   
for (var i = 0, len = argumentsArray.length; i < len; i++) {
    /* Pass the argumentsArray[i]
        for each then call, i want to be able to pass
        the current argumentsArray value
    */
    result = result.then(aJaxCall);
}

So far i tried with properties to the aJaxCall function itself and then handle it with arguments.calee.prop

for (var i = 0, len = argumentsArray.length; i < len; i++) {
    aJaxCall.prop = argumentsArray[i];
    result = result.then(aJaxCall);
}

and then within the aJaxCall function i tried to get the parameters like this:

arguments.callee.prop

but it is always binding the last element in the argumentsArray, cause the for loop finish and the .then is fired later in the cycle. Any suggestions are highly appreciated.

sla55er
  • 791
  • 1
  • 8
  • 16

1 Answers1

1

You can create a method that returns an anonymous function that calls ajaxCall with the passed parameters:

var callWithArgs = function(arg) {
  return function () {
     return ajaxCall(arg);
  }
}

for (var i = 0, len = argumentsArray.length; i < len; i++) {
    result = result.then(callWithArgs(argumentsArray[i]));
}
joeltine
  • 1,610
  • 17
  • 23