Concurrency

Use Promises, not callbacks

Callbacks aren’t clean, and they cause excessive amounts of nesting. With ES2015/ES6,
Promises are a built-in global type. Use them!

Bad:

  1. import { get } from 'request';
  2. import { writeFile } from 'fs';
  3. get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (requestErr, response) => {
  4. if (requestErr) {
  5. console.error(requestErr);
  6. } else {
  7. writeFile('article.html', response.body, (writeErr) => {
  8. if (writeErr) {
  9. console.error(writeErr);
  10. } else {
  11. console.log('File written');
  12. }
  13. });
  14. }
  15. });

Good:

  1. import { get } from 'request';
  2. import { writeFile } from 'fs';
  3. get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
  4. .then((response) => {
  5. return writeFile('article.html', response);
  6. })
  7. .then(() => {
  8. console.log('File written');
  9. })
  10. .catch((err) => {
  11. console.error(err);
  12. });

Async/Await are even cleaner than Promises

Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await
which offer an even cleaner solution. All you need is a function that is prefixed
in an async keyword, and then you can write your logic imperatively without
a then chain of functions. Use this if you can take advantage of ES2017/ES8 features
today!

Bad:

  1. import { get } from 'request-promise';
  2. import { writeFile } from 'fs-promise';
  3. get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
  4. .then((response) => {
  5. return writeFile('article.html', response);
  6. })
  7. .then(() => {
  8. console.log('File written');
  9. })
  10. .catch((err) => {
  11. console.error(err);
  12. });

Good:

  1. import { get } from 'request-promise';
  2. import { writeFile } from 'fs-promise';
  3. async function getCleanCodeArticle() {
  4. try {
  5. const response = await get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');
  6. await writeFile('article.html', response);
  7. console.log('File written');
  8. } catch(err) {
  9. console.error(err);
  10. }
  11. }