在JavaScript中,處理異步操作的常見方法有以下幾種:
function asyncOperation(callback) {
setTimeout(() => {
const result = '異步操作結果';
callback(result);
}, 1000);
}
function handleResult(result) {
console.log('處理結果:', result);
}
asyncOperation(handleResult);
.then()
方法來處理成功的結果,使用.catch()
方法來處理錯誤。function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = '異步操作結果';
resolve(result);
}, 1000);
});
}
asyncOperation()
.then(handleResult)
.catch(error => console.error('發生錯誤:', error));
async
關鍵字,我們可以在函數內部使用await
關鍵字等待一個Promise的結果。async function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = '異步操作結果';
resolve(result);
}, 1000);
});
}
async function main() {
try {
const result = await asyncOperation();
handleResult(result);
} catch (error) {
console.error('發生錯誤:', error);
}
}
main();
以上就是在JavaScript中處理異步操作的三種常見方法。在實際開發中,可以根據具體需求選擇合適的方法。