首頁歷史 > 正文

如何寫出乾淨的js程式碼(併發錯誤處理註釋篇)文末有驚喜

2022-03-23由 Null不等於undefine 發表于 歷史

一。

併發

避免回撥

回撥很混亂,會導致程式碼巢狀過深,使用

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程式碼”的最後一篇,往後會更新一些其他型別的前端文章,歡迎大家閱讀。

附上今日美圖嘿嘿

如何寫出乾淨的js程式碼(併發/錯誤處理/註釋篇)文末有驚喜

頂部