在JavaScript中,處理異步操作的常見方法有以下幾種:
function asyncOperation(callback) {
setTimeout(() => {
const result = '異步操作結果';
callback(result);
}, 1000);
}
asyncOperation((result) => {
console.log('回調函數接收到結果:', result);
});
.then()
和.catch()
方法來處理成功或失敗的結果。function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = '異步操作結果';
resolve(result); // 成功時調用resolve
// reject('出錯了'); // 失敗時調用reject
}, 1000);
});
}
asyncOperation()
.then((result) => {
console.log('Promise成功:', result);
})
.catch((error) => {
console.log('Promise失敗:', error);
});
async function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = '異步操作結果';
resolve(result);
}, 1000);
});
}
async function main() {
try {
const result = await asyncOperation();
console.log('async/await成功:', result);
} catch (error) {
console.log('async/await失敗:', error);
}
}
main();
load
事件。const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const result = JSON.parse(xhr.responseText);
console.log('事件監聽成功:', result);
}
};
xhr.send();
這些方法可以根據具體需求和場景選擇使用,以實現更好的異步處理效果。