mnowotka
mnowotka

Reputation: 17228

How to construct an array of jquery promises?

Let's say I have an async function returning a promise. I would like to chain a lot of these functions, each one with different arguments.

Function that will execute this array looks like this:

function executePromiseQueueSync(queue){
    var seed = $.Deferred(),
        finalPromise;

    _reduce(queue, function(memo, promise){
        return memo.then(promise);
    }, seed.promise());

    seed.resolve();
    return finalPromise;
}

I saw some functions accepting an array of promises and executing them synchronously. The problem is I don't know how to create such an array. Example:

var promiseQueue = [];
promiseQueue.push(AsynchEvent(someArg)); // WRONG: this is function call and will be executed immediately

Another:

var promiseQueue = [];
promiseQueue.push(AsynchEvent); // WRONG: at some point I will have to apply this with arguments

So - is there a way to put a function returning a promise into an array without executing it?

Upvotes: 2

Views: 227

Answers (1)

fredrik
fredrik

Reputation: 6638

Update after your edit:

Well it would be good if you included that info from the beginning, so here goes an attempt.

I'll assume that the first input is known and that returns from the last function should go into the next one in the list.

In that case we still define and add to the Queue as before:

var promiseQueue = [];
promiseQueue.push(AsynchEvent);

But we'll need to modify the loop abit. I'll make it into a function just to show how it could be used.

function calcPromise(initialArg) {
  aggregateArg = initialArg;
  for (var i = 0; i < myStringArray.length; i++) {
    aggregateArg = promiseQueue[i](aggregateArg);
  }
  return aggregateArg;
}

Keep in mind that this is JavaScript - what you return from one function and feeds to the next can be completely different between two iterations of this function. For example

  • promiseQueue[0] can expect an int and return a JSON struct.
  • promiseQueue[1] can expect a JSON struct and return a string.
  • and so on.

Upvotes: 1

Related Questions