Friday, 9 December 2016

Not sure if smart or stupid

I've been working with promises for quite a while now and have always had the desire to have nice clean promise chains. Since that means that each function in the chain has to receive the exact response from the previous resolved promise that usually meant that functions were written specifically for the promise chain and were otherwise useless.So I thought of a pattern that addresses this in a way, and I would like to get some feedback if this seems ok or if anybody can foresee issues here that I'm not yet seeing.exports.inviteToWorkspace = (workspaceId, role, account) => { if(account) return run(account); return (account) => { if(!account) return Promise.reject('Missing account document as a result of previous promise'); return run(account); }; function run(account){ // this is where the magic happens return Promise.resolve(); } }; The inviteToWorkspace function can be called either as a standalone function passing three parameters to it. Or if the account parameter is missing the returned function will receive it from the promise in the previous resolve in the chain.For example.You can call it as standalone.inviteToWorkspace(workspaceId, req.payload.role, accountDoc);You can put it in a chain provided that createAccount returns the accountDoccreateAccount(req.payload.email).then(inviteToWorkspace(workspaceId, req.payload.role));Is this ok? Is there a better way to achieve this?

Submitted December 09, 2016 at 08:47AM by icanevenificant

No comments:

Post a Comment