JavaScript異步編程的常見模式有以下幾種:
function asyncOperation(callback) {
setTimeout(() => {
const result = '異步操作完成';
callback(result);
}, 1000);
}
asyncOperation((result) => {
console.log(result); // 輸出 "異步操作完成"
});
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = '異步操作完成';
resolve(result);
}, 1000);
});
}
asyncOperation()
.then((result) => {
console.log(result); // 輸出 "異步操作完成"
})
.catch((error) => {
console.error(error);
});
async function main() {
try {
const result = await asyncOperation();
console.log(result); // 輸出 "異步操作完成"
} catch (error) {
console.error(error);
}
}
main();
document.addEventListener('click', (event) => {
console.log('按鈕被點擊了');
});
setTimeout(() => {
console.log('定時器觸發(fā)');
}, 1000);
const promise1 = new Promise((resolve) => setTimeout(resolve, 1000, 'one'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 2000, 'two'));
Promise.all([promise1, promise2])
.then((values) => {
console.log(values); // 輸出 ['one', 'two']
})
.catch((error) => {
console.error(error);
});
Promise.race([promise1, promise2])
.then((value) => {
console.log(value); // 輸出 'one'
})
.catch((error) => {
console.error(error);
});
這些模式可以根據(jù)實際需求和場景進行選擇和組合,以實現(xiàn)高效、易讀的異步編程。