1.
console.log("Start");
for (let i = 0; i < 3; i++) {
Promise.resolve().then(() => {
console.log("Inside the loop: " + i);
});
}
console.log("End");
//输出结果:
Start
End
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
//
2.
onsole.log("Start");
async function myFunction() {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => {
setTimeout(() => {
console.log("Inside the loop: " + i);
resolve();
}, 1000);
});
}
}
myFunction().then(() => {
console.log("End");
});
//输出结果:
Start
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
End
//
异步执行完之后再执行同步示例
最新推荐文章于 2024-05-08 22:21:54 发布