//示意同步代码,这个是最普通、最常见的场景(普通的脚本文件中最多)
function sleepS(second){console.log(`start time point:${new Date().toLocaleTimeString()}`);let start = new Date();let startMs = start.getTime();let reachTime = false;do {let cur = new Date();let curMs = cur.getTime();if((curMs - startMs) > 1000*second){reachTime = true;}}while(!reachTime);console.log(`end time point:${new Date().toLocaleTimeString()}`);
}
console.log('this is first line!');
sleepS(2);
sleepS(3);
console.log('this is last line!');
function asyncCode(){console.log(`this is first line!`);setTimeout(()=>{console.log(`this 3, is called,by task queue!`);},1);console.log(`this 2!`);
}asyncCode();
该函数输出如下:
this is first line!
this 2!
this 3, is called,by task queue!
该示例说明:
const bar = () => console.log('bar')const baz = () => console.log('baz')const foo = () => {console.log('foo')setTimeout(bar, 0) //宏任务再下一次队列开始时执行new Promise((resolve, reject) =>{//promise中的代码是主线程中同步执行的,一般是负责触发调用异步的函数,很快完成,不会阻塞console.log("after foo,befor baz");resolve('应该在 baz 之后、bar 之前')}).then(resolve => console.log(resolve))baz()
}foo()
上一篇:基于 SSH 的视频教学平台
下一篇:多模太大模型清单收集