Save the variables promises -for-results, and you can use them later in the final, when they guarantee that they will be executed, and therefore their value can be obtained using .value() synchronously
function insertUser(user, cb) { return bookshelf.transaction(function(t) { var key = user.key; var devID = Developer.forge({key: key}) .fetch({require: true, transacting: t}) .call("get", "id"); var addressID = devID.then(function() { return Address.forge(user.address).fetch({require: true, transacting: t}) }).call("get", "addressId"); var financialID = addressModel.then(function() { return Financial.forge(user.financial).save(null, {transacting: t}) }).call("get", "financialId"); var userModel = financialID.then(function() { var userEntity = user.personal; userEntity.addressId = addressID.value(); userEntity.developerId = devID.value(); userEntity.financialId = financialID.value(); return User.forge(userEntity).save(null, {transacting: t}); }); return userModel.then(function(userModel) { logger.info('saved user: ', userModel); logger.info('commiting transaction'); t.commit(userModel); }).catch(function(e) { t.rollback(e); throw e; }); }); } .then(function(model) { logger.info(model, ' successfully saved'); return Promise.resolve(respond.success({userId: model.get('userId')})); }) .catch(function(err) { logger.error(err, ' occurred'); return Promise.reject(new DatabaseError('Unable to write user to database due to error ', err.message)); })};
Another way is to use Promise.join :
function insertUser(user, cb) { return bookshelf.transaction(function(t) { var key = user.key; var devID = Developer.forge({key: key}) .fetch({require: true, transacting: t}) .call("get", "id"); var addressID = devID.then(function() { return Address.forge(user.address).fetch({require: true, transacting: t}) }).call("get", "addressId"); var financialID = addressModel.then(function() { return Financial.forge(user.financial).save(null, {transacting: t}) }).call("get", "financialId"); var userModel = Promise.join(devID, addressID, financialID, function(devID, addressID, financialID) { var userEntity = user.personal; userEntity.addressId = addressID; userEntity.developerId = devID; userEntity.financialId = financialID; return User.forge(userEntity).save(null, {transacting: t}); }); return userModel.then(function(userModel) { logger.info('saved user: ', userModel); logger.info('commiting transaction'); t.commit(userModel); }).catch(function(e) { t.rollback(e); throw e; }); }); } .then(function(model) { logger.info(model, ' successfully saved'); return Promise.resolve(respond.success({userId: model.get('userId')})); }) .catch(function(err) { logger.error(err, ' occurred'); return Promise.reject(new DatabaseError('Unable to write user to database due to error ', err.message)); })};
source share