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(){})
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.