在JavaScript中,方法的执行顺序遵循以下基本规则:
console.log('Start');
function syncFunction() {
console.log('Sync Function');
}
syncFunction();
console.log('End');
输出:
Start
Sync Function
End
console.log('Start');
setTimeout(() => {
console.log('Async Function with Callback');
}, 0);
console.log('End');
输出:
Start
End
Async Function with Callback
console.log('Start');
new Promise((resolve) => {
setTimeout(() => {
resolve('Async Function with Promise');
}, 0);
}).then((result) => {
console.log(result);
});
console.log('End');
输出:
Start
End
Async Function with Promise
console.log('Start');
async function asyncFunction() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Async Function with async/await');
}, 0);
});
}
(async () => {
const result = await asyncFunction();
console.log(result);
})();
console.log('End');
输出:
Start
End
Async Function with async/await
function asyncOperation1() {
return new Promise((resolve) => {
setTimeout(() => resolve('Operation 1'), 1000);
});
}
function asyncOperation2() {
return new Promise((resolve) => {
setTimeout(() => resolve('Operation 2'), 1000);
});
}
asyncOperation1()
.then((result) => {
console.log(result);
return asyncOperation2();
})
.then((result) => {
console.log(result);
});
async function runOperations() {
const result1 = await asyncOperation1();
console.log(result1);
const result2 = await asyncOperation2();
console.log(result2);
}
runOperations();
通过以上方法,可以有效地控制JavaScript中方法的执行顺序,确保代码的正确性和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云