Jonathan Dumaine
Jonathan Dumaine

Reputation: 5756

How to use promises in functions that can be called in various orders?

My goal is pretty simple. I have a bunch of async utility functions that are called in various orders.

Right not it's like this:

doSomething(doNextThing(doFinalThing));

But it's becoming unwieldy. My goal is to have a syntax like this:

doSomething.then(doNextThing).then(doFinalThing)

but with the ability for the order to change:

doNextThing.then(doSomething).then(doFinalThing)

How would I go about implementing these functions so that they are all promise-aware?

Upvotes: 0

Views: 78

Answers (2)

hugomg
hugomg

Reputation: 69934

In general, what you do in this sort of situation is abstract the parts that vary into variables or function parameters:

function chainStuff(first, second, third){
   return first.then(second).then(thrid)
}

You can then choose at runtime what callbacks you bind to each parameter (first, second, third)

if(condition){
    return chainStuff(doSomething, doNextThing, doFinalThing)
}else{
    return chainStuff(doNextThing, doSomething, doFinalThing)
}

Upvotes: 0

Lee
Lee

Reputation: 13542

Each function needs to return a promise that completes when its async task is complete. Check out one of the many existing promise libraries. An excellent one is Q.

Then you'll call the functions in sequence, like this:

var promiseForFinalResult = doSomething().then(doNextThing).then(doFinalThing);

that assumes that each function takes only one argument--the result of the previous function.


Using "Q" the implementation of doSomething() might look somthing like this:

function doSomething() {
   var D = Q.defer();
   kickOffSomeAsyncTask(function(err, result) {
       // this callback gets called when the async task is complete
       if(err) {  
           D.fail(err); 
           return;
       }
       D.resolve(result);
   });
   return D.promise;
}

Have a look at the docs for "Q". The docs for Q.defer are located here, but you might want to read some of the preceding stuff before diving directly into deferreds.

Upvotes: 1

Related Questions