一、使用Promise,别使用Callbacks
Callbacks不够简洁,它会产生大量的嵌套。在ES6中,最好使用Promises
Bad:import { get } from 'request';import { writeFile } from 'fs';get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (requestErr, response) => { if (requestErr) { console.error(requestErr); } else { writeFile('article.html', response.body, (writeErr) => { if (writeErr) { console.error(writeErr); } else { console.log('File written'); } }); }});Good:import { get } from 'request';import { writeFile } from 'fs';get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') .then((response) => { return writeFile('article.html', response); }) .then(() => { console.log('File written'); }) .catch((err) => { console.error(err); });
二、Async/Await 比Promises更简洁
Promises比callbacks简洁很多,但 ES2017/ES8 提出了async/await 方法,提供了更简洁的解决办法。你只需要在函数前面加一个 async关键字,然后就可以不用then链式方法写逻辑了。如果能用 ES2017/ES8现在就开始用吧。
Bad:import { get } from 'request-promise';import { writeFile } from 'fs-promise';get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') .then((response) => { return writeFile('article.html', response); }) .then(() => { console.log('File written'); }) .catch((err) => { console.error(err); });Good:import { get } from 'request-promise';import { writeFile } from 'fs-promise';async function getCleanCodeArticle() { try { const response = await get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin'); await writeFile('article.html', response); console.log('File written'); } catch(err) { console.error(err); }}