浅谈JavaScript 代码整洁之道(14)
async/await 比 Promise 还整洁
与回调相当,Promise 已经相当整洁了,但 ES7 带来了更整洁的解决方案 —— async 和 await。你要做的事情就是在一个函数前加上 async 关键字,然后写下命令形式的逻辑,而不再需要 then 链。现在可以使用这个 ES7 特性带来的便利!
不好:
require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
.then(function(response) {
return require('fs-promise').writeFile('article.html', response);
})
.then(function() {
console.log('File written');
})
.catch(function(err) {
console.error(err);
})
好:
async function getCleanCodeArticle() {
try {
var request = await require('request-promise')
var response = await request.get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');
var fileHandle = await require('fs-promise');
await fileHandle.writeFile('article.html', response);
console.log('File written');
} catch(err) {
console.log(err);
}
}
错误处理
抛出错误是件好事!这表示运行时已经成功检测到程序出错了,它停止当前调用框上的函数执行,并中止进程(在 Node 中),最后在控制台通知你,并输出栈跟踪信息。
不要忽略捕捉到的错误
捕捉到错误却什么也不错,你就失去了纠正错误的机会。多数情况下把错误记录到控制台(console.log)也不比忽略它好多少,因为在少量的控制台信息中很难发现这一条。如果尝试在 try/catch 中封装代码,就意味着你知道这里可能发生错,你应该在错误发生的时候有应对的计划、或者处理办法。
不好:
try {
functionThatMightThrow();
} catch (error) {
console.log(error);
}
好:
try {
functionThatMightThrow();
} catch (error) {
// 选择之一(比 console.log 更闹心):
console.error(error);
// 另一个选择:
notifyUserOfError(error);
// 另一个选择:
reportErrorToService(error);
// 或者所有上述三种选择!
}
不要忽视被拒绝的Promise
这一条与不要忽略从 try/catch 捕捉到的错误有相同的原因。
不好:
getdata()
.then(data => {
functionThatMightThrow(data);
})
.catch(error => {
console.log(error);
});
好:
getdata()
.then(data => {
functionThatMightThrow(data);
})
.catch(error => {
// 选择之一(比 console.log 更闹心):
console.error(error);
// 另一个选择:
notifyUserOfError(error);
// 另一个选择:
reportErrorToService(error);
// 或者所有上述三种选择!
});
内容版权声明:除非注明,否则皆为本站原创文章。
