JavaScript通过回调函数、Promises和async
/await
来处理异步操作。
示例(使用Promises):
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Operation complete');
}, 1000);
});
}
asyncOperation().then(result => {
console.log(result);
});
示例(使用async/await):
async function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Operation complete');
}, 1000);
});
}
async function runAsync() {
const result = await asyncOperation();
console.log(result);
}
runAsync();