2

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?

3
  • Take a look at the bind function. Commented Mar 8, 2013 at 9:20
  • Look at the edited question, function "executePromiseQueueSync". How bind would help me in this case? Commented Mar 8, 2013 at 9:47
  • Promises aren't executed and it's hard to know exactly what you are trying to achieve. Suggest you try to explain in straightforward terms that don't assume a particular solution. Commented Mar 9, 2013 at 0:48

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Look at the question once again - it's edited now. You will see my problem.
Oh, yeah - perhaps I should let you know. I've updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.