On Jul 7, 2013, at 12:15 AM, Paul Tiseo wrote:
>
> For example, slightly more tangible:
> 1. validate email
> 2. load three different template files (when.all() or when.join()?)
> 3. merge data (including that email) into those three templates separately
> 4. email each final item (all()? join()? when/parallel?)
> 5. save email to a database (then()?)
Hm let's see how I would structure this. First off, let's start with a function:
function readTemplate(templateName) {
// return promise for the template text
// Probably nodefn.call ?
}
Takes as input a filename, and returns a promise for the corresponding text. Then let's make a getTemplates function
function getTemplates() {
var templates = ["template1.txt", …. ];
return when.map(templates, readTemplate);
}
I suppose we have different ways to proceed now, what I am thinking however is this: Turn the templates into functions that given data input produce the substituted result. Most template engines offer you this compiled function step already, otherwise it might look something like this:
function compile(template) {
return function(data) {
// Merge data with template and return result
}
}
Then my getTemplates function would probably rather be:
function getTemplates() {
var templates = ["template1.txt", …. ];
return when.map(when.map(templates, readTemplate), compile);
}
now our getTemplates will be returning a promised array of functions. You also already have the method validateEmail which returns a promise. So then you can start the processing by something like:
parallel(getTemplates(), validateEmail())
.then(processForms) // handles item 4
.then(storeEmails) // handles item 5
.otherwise(handleErrors);
processForms might look something like this, taking as input the array of already substituted forms:
function processForms(forms) {
return parallel(when.map(forms, processSingleForm));
}
function processSingleForm(form) {
// Arrange to email the form, return promise
// The promise will either fulfill with what storeEmails expects, or reject if it fails to send
}
You get the idea I hope. You still will need a number of functions to do the individual parts in that large chain of steps you had, they just don't need to use callbacks, they can just expect a value for the most part, and return a value or promise. And you can more or less set up a single point of failure at the end of the chain of promises.
There's probably other ways around this question. That's my thinking of it as of the here and now.
Haris Skiadas