Should we use Promises?
Promises have the potential to significantly clear up a lot of async code that we have laying about. I think it's worth trying it out on a small scale and seeing whether or not it would be a good fit for the codebase we have.
:+1:
We recently switched our containers to io.js and using promises whenever we have async operations. So far everyone on the team like it. it does add some boilerplate but I think it's worth it for the readability of the client that calling the promises.
I would suggest to try to use named functions whenever possible:
login().then(getUsers).then(saveAttachments).then(done).catch(error)
An example with some sample code similar to some stuff we have in Anvil Connect
Without Promises:
function someMiddleware(req, res, next) {
Model.doSomeWork({ opt: 'val' }, function (err, model) {
if (err) { return next(err); }
if (!model) { return next(new Error('Invalid request')); }
model.doSomethingElse(function (err, result) {
if (err) { return next(err); }
if (!result) { return next(new Error('Invalid options')); }
if (result.x === 1) {
model.doAnotherThing({ opt: result.y }, function (err, attr) {
if (err) { return next(err); }
if (attr) {
res.render('view', { data: result.attrs[attr] });
} else {
res.render('view', { data: result });
}
});
} else {
res.render('view', { data: result });
}
});
});
}
With Promises:
function someMiddleware(req, res, next) {
Model.doSomeWork({ opt: 'val' }).then(function (model) {
if (!model) { throw new Error('Invalid request'); }
return model.doSomethingElse();
}).then(function (result) {
if (!result) { throw new Error('Invalid options'); }
if (result.x === 1) {
return model.doAnotherThing({ opt: result.y }).then(function (attr) {
return attr ? result.attrs[attr] : result;
});
} else {
return result;
}
}).then(function (data) {
res.render('view', { data: data });
}).catch(function (err) {
next(err);
});
}