samedi 9 mai 2015

How to use results from Q Promise inside and outside of promise.spread

I recently started using the q promise javascript library for my Node.js application. In my code I have a conditional that determines if I should execute 1 or 3 promise methods. I then want to execute the array of promise-returning methods and perform additional processing on the results.

Question: How do I use the results inside and outside .spread(...), so I can pass the result to other methods?

Some background: I am building a REST API, where depending on the values of the POSTed JSON body, I have to insert records into the DB using Sequelize first, get a response (so I know the auto-generated primary key), then insert records in other tables using that primary key.

var promiseMethods;

var someParam1, someParam2, someParam3 = 'Hello World';

if (someCondition == true) {

    promiseMethods = [promiseMethod1(someParam1)];
} else {
    promiseMethods = [
        promiseMethod1(someParam1),
        promiseMethod2(someParam2),
        promiseMethod3(someParam3)];
}

Q.all(promiseMethods)
    .spread(function(promseResult1,
                     promiseResult2,
                     promiseResult3) {

    var model = {
        result: promiseResult1
    };

    //Other code removed for brevity.

    return Database.save(model)
});

Aucun commentaire:

Enregistrer un commentaire