2

I am doing something like this in which first function is dependent dependent on second .

let findOrg = () => {
    return new Promise((resolve, reject) => {
        db.organization.find({
                where: data
            })
            .then(org => {
                return resolve(org);
            }).catch(err => {
                reject(err);
            });
    }); };

let createOrg = org => {
    return new Promise((resolve, reject) => {
        if (org) {
            return resolve(org);
        }
        db.organization.build(data)
            .save()
            .then((org) => {
                return resolve(org);
            }).catch(err => {
                reject(err);
            });
    }); };

findOrg()
    .then(org => { //going to find org
        return createOrg(org); //then going to make org
    }).then(newOrg => {
        res.data(mapper.toModel(newOrg)); //then mapping
    }).catch(err => {
        return res.failure(err);
    });

in both above function findOrg and createOrg new promise (ES6) are created

My ques is -- 1. how we can solve this in Bluebird promise library (in sequence if one function is dependent on other) like

async.waterfall([
function(){},
function(){}],
function(){})
  1. here 2 promises are created .is there any way i
hardy
  • 880
  • 2
  • 13
  • 30

1 Answers1

0

You can use bluebird's Promise.reduce or create your own waterfall (chain) function like this as alternative.

But: your code has unnecessary overhead in using the promise constructor antipattern: you can write it without using new Promise, and with .bind you also avoid creating inline functions explicitly, ... like this:

let findOrg = () => db.organization.find({where: data});

let createOrg = org => org || db.organization.build(data).save();

findOrg()
    .then(createOrg)
    .then(mapper.toModel.bind(mapper))
    .then(res.data.bind(res))
    .catch(res.failure.bind(res));

This is quite clean in my opinion.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286
  • you don't think so promise.reduce will work like `async.each` ?? in which it takes one element and make execution for it .. then pick other and make same execution for other also .. i want unique executions for different fuctions – hardy Apr 16 '17 at 20:30
  • `promise.reduce` can take an array of promises, and execute them one after the other. The documentation says: *If the reducer function returns a promise, then the result of the promise is awaited, before continuing with next iteration.* To my understanding of your question, that is exactly what you want. – trincot Apr 16 '17 at 21:25