寫好 JavaScript 異步代碼的幾個(gè)推薦做法
今天給大家來(lái)推薦幾個(gè)寫好 JavaScript 異步代碼的推薦做法,每種場(chǎng)景都有一個(gè)對(duì)應(yīng)的 eslint 規(guī)則,大家可以選擇去配置一下。
no-async-promise-executor
不建議將 async 函數(shù)傳遞給 new Promise 的構(gòu)造函數(shù)。
// :x:
new Promise(async (resolve, reject) => {});
// :white_check_mark:
new Promise((resolve, reject) => {});
首先,你在 Promise 的構(gòu)造函數(shù)里去使用 async ,那么包裝個(gè) Promise 可能就是沒啥必要的。另外,如果 async 函數(shù)拋出了異常,新構(gòu)造的 promise 實(shí)例并不會(huì) reject ,那么這個(gè)錯(cuò)誤就捕獲不到了。
no-await-in-loop
不建議在循環(huán)里使用 await ,有這種寫法通常意味著程序沒有充分利用 JavaScript 的事件驅(qū)動(dòng)。
// :x:
for (const url of urls) {
const response = await fetch(url);
}
建議將這些異步任務(wù)改為并發(fā)執(zhí)行,這可以大大提升代碼的執(zhí)行效率。
// :white_check_mark:
const responses = [];
for (const url of urls) {
const response = fetch(url);
responses.push(response);
}
await Promise.all(responses);
no-promise-executor-return
不建議在 Promise 構(gòu)造函數(shù)中返回值, Promise 構(gòu)造函數(shù)中返回的值是沒法用的,并且返回值也不會(huì)影響到 Promise 的狀態(tài)。
// :x:
new Promise((resolve, reject) => {
return result;
});
正常的做法是將返回值傳遞給 resolve ,如果出錯(cuò)了就傳給 reject 。
// :white_check_mark:
new Promise((resolve, reject) => {
resolve(result);
});
require-atomic-updates
不建議將賦值操作和 await 組合使用,這可能會(huì)導(dǎo)致條件競(jìng)爭(zhēng)。
看看下面的代碼,你覺得 totalPosts 最終的值是多少?
// :x:
let totalPosts = 0;
async function getPosts(userId) {
const users = [{ id: 1, posts: 5 }, { id: 2, posts: 3 }];
await sleep(Math.random() * 1000);
return users.find((user) => user.id === userId).posts;
}
async function addPosts(userId) {
totalPosts += await getPosts(userId);
}
await Promise.all([addPosts(1), addPosts(2)]);
console.log('Post count:', totalPosts);
totalPosts 會(huì)打印 3 或 5,并不會(huì)打印 8,你可以在瀏覽器里自己試一下。
問題在于讀取 totalPosts 和更新 totalPosts 之間有一個(gè)時(shí)間間隔。這會(huì)導(dǎo)致競(jìng)爭(zhēng)條件,當(dāng)值在單獨(dú)的函數(shù)調(diào)用中更新時(shí),更新不會(huì)反映在當(dāng)前函數(shù)范圍中。因此,兩個(gè)函數(shù)都會(huì)將它們的結(jié)果添加到 totalPosts 的初始值0。
避免競(jìng)爭(zhēng)條件正確的做法:
// :white_check_mark:
let totalPosts = 0;
async function getPosts(userId) {
const users = [{ id: 1, posts: 5 }, { id: 2, posts: 3 }];
await sleep(Math.random() * 1000);
return users.find((user) => user.id === userId).posts;
}
async function addPosts(userId) {
const posts = await getPosts(userId);
totalPosts += posts; // variable is read and immediately updated
}
await Promise.all([addPosts(1), addPosts(2)]);
console.log('Post count:', totalPosts);
max-nested-callbacks
防止回調(diào)地獄,避免大量的深度嵌套:
/* eslint max-nested-callbacks: ["error", 3] */
// :x:
async1((err, result1) => {
async2(result1, (err, result2) => {
async3(result2, (err, result3) => {
async4(result3, (err, result4) => {
console.log(result4);
});
});
});
});
// :white_check_mark:
const result1 = await asyncPromise1();
const result2 = await asyncPromise2(result1);
const result3 = await asyncPromise3(result2);
const result4 = await asyncPromise4(result3);
console.log(result4);
回調(diào)地獄讓代碼難以閱讀和維護(hù),建議將回調(diào)都重構(gòu)為 Promise 并使用現(xiàn)代的 async/await 語(yǔ)法。
no-return-await
返回異步結(jié)果時(shí)不一定要寫 await ,如果你要等待一個(gè) Promise ,然后又要立刻返回它,這可能是不必要的。
// :x:
async () => {
return await getUser(userId);
}
從一個(gè) async 函數(shù)返回的所有值都包含在一個(gè) Promise 中,你可以直接返回這個(gè) Promise 。
// :white_check_mark:
async () => {
return getUser(userId);
}
當(dāng)然,也有個(gè)例外,如果外面有 try...catch 包裹,刪除 await 就捕獲不到異常了,在這種情況下,建議明確一下意圖,把結(jié)果分配給不同行的變量。
// :-1:
async () => {
try {
return await getUser(userId);
} catch (error) {
// Handle getUser error
}
}
// :+1:
async () => {
try {
const user = await getUser(userId);
return user;
} catch (error) {
// Handle getUser error
}
}
prefer-promise-reject-errors
建議在 reject Promise 時(shí)強(qiáng)制使用 Error 對(duì)象,這樣可以更方便的追蹤錯(cuò)誤堆棧。
// :x:
Promise.reject('An error occurred');
// :white_check_mark:
Promise.reject(new Error('An error occurred'));
node/handle-callback-err
強(qiáng)制在 Node.js 的異步回調(diào)里進(jìn)行異常處理。
// :x:
function callback(err, data) {
console.log(data);
}
// :white_check_mark:
function callback(err, data) {
if (err) {
console.log(err);
return;
}
console.log(data);
}
在 Node.js 中,通常將異常作為第一個(gè)參數(shù)傳遞給回調(diào)函數(shù)。忘記處理這些異常可能會(huì)導(dǎo)致你的應(yīng)用程序出現(xiàn)不可預(yù)知的問題。
如果函數(shù)的第一個(gè)參數(shù)命名為 err 時(shí)才會(huì)觸發(fā)這個(gè)規(guī)則,你也可以去 .eslintrc 文件里自定義異常參數(shù)名。
node/no-sync
不建議在存在異步替代方案的 Node.js 核心 API 中使用同步方法。
// :x:
const file = fs.readFileSync(path);
// :white_check_mark:
const file = await fs.readFile(path);
在 Node.js 中對(duì) I/O 操作使用同步方法會(huì)阻塞事件循環(huán)。大多數(shù)場(chǎng)景下,執(zhí)行 I/O 操作時(shí)使用異步方法是更好的選擇。
@typescript-eslint/await-thenable
不建議 await 非 Promise 函數(shù)或值。
// :x:
function getValue() {
return someValue;
}
await getValue();
// :white_check_mark:
async function getValue() {
return someValue;
}
await getValue();
@typescript-eslint/no-floating-promises
建議 Promise 附加異常處理的代碼。
// :x:
myPromise()
.then(() => {});
// :white_check_mark:
myPromise()
.then(() => {})
.catch(() => {});
養(yǎng)成個(gè)好的習(xí)慣,永遠(yuǎn)做好異常處理!
@typescript-eslint/no-misused-promises
不建議將 Promise 傳遞到并非想要處理它們的地方,例如 if 條件。
// :x:
if (getUserFromDB()) {}
// :white_check_mark: :-1:
if (await getUserFromDB()) {}
更推薦抽一個(gè)變量出來(lái)提高代碼的可讀性。
// :white_check_mark: :+1:
const user = await getUserFromDB();
if (user) {}