js的錯誤處理?一.并發回調很混亂,會導緻代碼嵌套過深,使用 Promise 替代回調,下面我們就來說一說關于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代碼”的最後一篇,往後會更新一些其他類型的前端文章,歡迎大家閱讀。
附上今日美圖嘿嘿
更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!