在 JavaScript 中,我们可以使用 Promise 和 async/await 的方式来实现按特定顺序执行函数的需求。
使用 Promise 的方式:
function func1() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Func1');
resolve();
}, 1000);
});
}
function func2() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Func2');
resolve();
}, 500);
});
}
function func3() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Func3');
resolve();
}, 1500);
});
}
func1()
.then(func2)
.then(func3);
使用 async/await 的方式:
function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function func1() {
console.log('Func1');
await sleep(1000);
}
async function func2() {
console.log('Func2');
await sleep(500);
}
async function func3() {
console.log('Func3');
await sleep(1500);
}
async function main() {
await func1();
await func2();
await func3();
}
main();
以上两种方式都实现了按特定顺序执行函数的需求,具体选择哪种方式取决于你自己的开发习惯和项目需求。