一.并发回调很混乱,会导致代码嵌套过深,使用 Promise 替代回调,下面我们就来说一说关于js的错误处理?我们一起去了解并探讨一下这个问题吧!

js的错误处理(如何写出干净的js代码)

js的错误处理

一.并发

避免回调

回调很混乱,会导致代码嵌套过深,使用 Promise 替代回调

// Don't ❌ getUser(function (err, user) { getProfile(user, function (err, profile) { getAccount(profile, function (err, account) { getReports(account, function (err, reports) { sendStatistics(reports, function (err) { console.error(err); }); }); }); }); }); // Do ✅ getUser() .then(getProfile) .then(getAccount) .then(getReports) .then(sendStatistics) .catch((err) => console.error(err)); // or using Async/Await ✅✅ async function sendUserStatistics() { try { const user = await getUser(); const profile = await getProfile(user); const account = await getAccount(profile); const reports = await getReports(account); return sendStatistics(reports); } catch (e) { console.error(err); } }

二. 错误处理

处理抛出的错误和 reject 的 promise

/ Don't ❌ try { // Possible erronous code } catch (e) { console.log(e); } // Do ✅ try { // Possible erronous code } catch (e) { // Follow the most applicable (or all): // 1- More suitable than console.log console.error(e); // 2- Notify user if applicable alertUserOfError(e); // 3- Report to server reportErrorToServer(e); // 4- Use a custom error handler throw new CustomError(e); }

三. 注释

可读的代码使你免于过度注释,因此,你应该只注释复杂的逻辑。

// Don't ❌ function generateHash(str) { // Hash variable let hash = 0; // Get the length of the string let length = str.length; // If the string is empty return if (!length) { return hash; } // Loop through every character in the string for (let i = 0; i < length; i ) { // Get character code. const char = str.charCodeAt(i); // Make the hash hash = (hash << 5) - hash char; // Convert to 32-bit integer hash &= hash; } } // Do ✅ function generateHash(str) { let hash = 0; let length = str.length; if (!length) { return hash; } for (let i = 0; i < length; i ) { const char = str.charCodeAt(i); hash = (hash << 5) - hash char; hash = hash & hash; // Convert to 32bit integer } return hash; }

本文是“如何写出高质量的js代码”的最后一篇,往后会更新一些其他类型的前端文章,欢迎大家阅读。

附上今日美图嘿嘿