Simplify async code with generators and promises
Asynchronous code is a necessary part of life when developing in JavaScript. Why not make it easy on yourself?
Start with promises. They reduce the need for callback functions and practically eliminate nested callbacks. If you aren’t already using them, you should be. My favorite library for promises is https://github.com/petkaantonov/bluebird
Then we have generators. They are a new feature introduced in ES6. You can read more about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
Even when using promises, async code can become unwieldy. Take a look at the following code.
getUser(id).then(function (user) {
return getCompany(user.companyId).then(function(company) {
return getUser(company.ceoId);
});
});
Assume id is already set and that all functions return promises. The code will return the user object for the CEO of the...