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('定时器触发');
}, 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);
});
这些模式可以根据实际需求和场景进行选择和组合,以实现高效、易读的异步编程。