本文共 1436 字,大约阅读时间需要 4 分钟。
来自推特上 Windows 故障分析的笑话 图片来源: 推上看到的笑话,Windows 故障分析的实现。 然后想起来 JavaScript 中如何实现这个 异步版本借助 这事很好实现。 function sleep(time) { return new Promise(resolve => { setTimeout(() => { resolve(); }, time); });} 创建一个 但, 所以使用起来应该像这样子, function testSleep() { console.log("will sleep for 1s"); sleep(1000).then(() => { console.log("will sleep for another 5s"); sleep(5000).then(() => { console.log("waked up"); }); });}testSleep(); 或者这样子: async function testSleep() { console.log("will sleep for 1s"); await sleep(1000); console.log("will sleep for another 5s"); await sleep(5000); console.log("waked up");}testSleep(); 测试 sleep 当然后者会更加优雅些,但本质上都是需要保证后续代码在 Promise 回调中执行。如何有回调之外的代码,则不会被阻断,这便是其缺点。 async function testSleep() { console.log("will sleep for 1s"); await sleep(1000); console.log("will sleep for another 5s"); await sleep(5000); console.log("waked up");}testSleep(); 代码未阻断的情况 同步版本不借助异步异步代码想阻断代码执行,那其实可以让代码原地跑,通过 function syncSleep(time) { const start = new Date().getTime(); while (new Date().getTime() - start < time) {}} 使用起来就和正常函数没区别了,对周围代码也没有要求必需得在回调什么的: console.log("start test sync sleep...");syncSleep(3000);console.log("sync sleep after 3s"); 测试同步版本的 sleep 方便是方便,但不建议使用这种方式,毕竟代码在空跑。如果需要这样的场景,你需要考虑是否可以修改下代码或换个设计,异步能满足大部分需求。 相关资源 |
转载地址:http://ygdkz.baihongyu.com/