3.1 創建 Promise 鏈
Promise 鏈 讓你可以按順序執行多個非同步操作,把一個操作的結果傳給下一個。這讓代碼更易讀易管理。而且,Promise 提供強大的錯誤處理功能,讓你可以創建健壯且不怕失敗的應用程式。
主要概念
Promise 鏈是透過從 then 方法返回一個新的 Promise 來建立的。每個 then 方法都返回一個新的 Promise,讓你可以構建一系列的非同步操作。
簡單的 Promise 鏈示例
在這個例子中,每個 then 方法執行自己的操作並將結果傳給下一個 then 方法。
JavaScript
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Step 1 completed');
}, 1000);
});
promise
.then((result) => {
console.log(result); // 輸出: Step 1 completed
return 'Step 2 completed';
})
.then((result) => {
console.log(result); // 輸出: Step 2 completed
return 'Step 3 completed';
})
.then((result) => {
console.log(result); // 輸出: Step 3 completed
})
.catch((error) => {
console.error(error);
});
含非同步操作的 Promise 鏈示例
在這個例子中,每個 then 方法會等待非同步操作完成後再執行下一步:
JavaScript
function asyncOperation(step) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${step} completed`);
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result); // 輸出: Step 1 completed
return asyncOperation('Step 2');
})
.then((result) => {
console.log(result); // 輸出: Step 2 completed
return asyncOperation('Step 3');
})
.then((result) => {
console.log(result); // 輸出: Step 3 completed
})
.catch((error) => {
console.error(error);
});
3.2 處理 Promise 鏈的錯誤
catch 方法用來處理 Promise 鏈中的錯誤。如果任何一個 Promise 出現錯誤,它會被傳遞到最近的 catch 方法。這讓你可以集中處理錯誤,提升代碼的可讀性和維護性。
錯誤處理示例
在這個例子中,Step 2 出現的錯誤被 catch 方法捕獲,接下來的 then 方法不會執行:
JavaScript
function asyncOperation(step, shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(`${step} failed`);
} else {
resolve(`${step} completed`);
}
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result);
return asyncOperation('Step 2', true); // 這個操作會失敗
})
.then((result) => {
console.log(result); // 這段代碼不會執行
return asyncOperation('Step 3');
})
.then((result) => {
console.log(result); // 這段代碼不會執行
})
.catch((error) => {
console.error('Error:', error); // 輸出: Error: Step 2 failed
});
在特定步驟的錯誤處理
有時需要在鏈中的特定步驟處理錯誤而不中斷整個鏈的執行。你可以在 then 和 catch 方法中嵌套來達成這種效果。
在特定步驟的錯誤處理示例
在這個例子中,Step 2 的錯誤被本地處理,並且鏈接繼續與恢復的值執行:
JavaScript
function asyncOperation(step, shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(`${step} failed`);
} else {
resolve(`${step} completed`);
}
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result);
return asyncOperation('Step 2', true).catch((error) => {
console.warn('Handled error in Step 2:', error);
return 'Recovered from Step 2 error';
});
})
.then((result) => {
console.log(result); // 輸出: Recovered from Step 2 error
return asyncOperation('Step 3');
})
.then((result) => {
console.log(result); // 輸出: Step 3 completed
})
.catch((error) => {
console.error('Error:', error); // 這段代碼不會執行
});
3.3 使用 finally
finally 方法用於在 Promise 成功或失敗後,無論如何都會執行的代碼。這對於執行一些結束操作很有用,比如資源清理。
finally 的使用示例:
JavaScript
function asyncOperation(step, shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(`${step} failed`);
} else {
resolve(`${step} completed`);
}
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result);
return asyncOperation('Step 2');
})
.then((result) => {
console.log(result);
return asyncOperation('Step 3');
})
.catch((error) => {
console.error('Error:', error);
})
.finally(() => {
console.log('All operations completed'); // 不論如何都會執行
});
在這個例子中,finally 方法無論發生錯誤與否,都會執行。
GO TO FULL VERSION