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.getElementById('myButton').addEventListener('click', () => {
console.log('按钮被点击');
});
const promise1 = asyncOperation1();
const promise2 = asyncOperation2();
Promise.all([promise1, promise2]).then(([result1, result2]) => {
console.log(result1, result2);
});
// 或者
Promise.race([promise1, promise2]).then((result) => {
console.log(result);
});