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('按鈕被點(diǎn)擊');
});
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);
});