惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
The Register - Security
The Register - Security
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The GitHub Blog
The GitHub Blog
博客园 - 司徒正美
罗磊的独立博客
U
Unit 42
S
SegmentFault 最新的问题
Y
Y Combinator Blog
博客园_首页
Hugging Face - Blog
Hugging Face - Blog
J
Java Code Geeks
Schneier on Security
Schneier on Security
Know Your Adversary
Know Your Adversary
C
Check Point Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Simon Willison's Weblog
Simon Willison's Weblog
V
Vulnerabilities – Threatpost
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
The Hacker News
The Hacker News
博客园 - 叶小钗
C
Cybersecurity and Infrastructure Security Agency CISA
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Latest news
Latest news
L
Lohrmann on Cybersecurity
A
About on SuperTechFans
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
S
Securelist
A
Arctic Wolf
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threatpost
Scott Helme
Scott Helme
博客园 - 聂微东
博客园 - 【当耐特】
T
Tenable Blog
I
Intezer
D
DataBreaches.Net
B
Blog RSS Feed
Security Latest
Security Latest
C
Cisco Blogs
T
Tor Project blog
N
Netflix TechBlog - Medium

博客园 - Liaofy

前端新范式:用 AI 提效开发,用 E2E 保证迭代质量 把SPA的加载速度提升一倍,有没有搞头? 使用mumu模拟器抓包 andriod app 如何在本地给 vue-router4 扩展功能? Vue3 路由优化,使页面初次渲染效率翻倍 【eslint 插件开发】禁用 location 跳转外部链接 vue 项目使用 charles 代理线上页面到本地后显示404 避免使用单个数字作为对象的key 高扩展弹出层组件设计实现(H5&小程序) 轻松搞懂POST与PUT的区别 vite(or rollup) 实现 webpackChunkName webapp项目架构畅想(vue3).md vite试玩:老项目启动从6分钟到秒开 修剪AST树减少webapck打包尺寸 【uniapp】改善中大型uniapp小程序项目开发体验 vscode 调试 webpack 打包 5分钟,搞清 Unicode 与 UTF-8 的区别 盘的转——使用缓动函数完成动画 多个请求间断失败,如何优雅处理?
deAsync.js 真正让异步变同步
Liaofy · 2021-09-06 · via 博客园 - Liaofy

卧槽!牛逼!IMBA!这就是我第一次看到这个库的心情。迫不及待的想要分享给大伙儿。

同步代码

众所周知,JS 是一门‘单线程’语言,一旦开始,就会从始至终、从上到下的执行完毕,非常的专一。

console.log(1)
console.log(2)
console.log(3)

// 1
// 2
// 3

异步代码

然而,老实人也有变心的一天。回调函数、Promise 让 JS 拥有了异步处理的能力。

console.log(1)
Promise.resolve()
  .then(() => console.log(2))

console.log(3)

// 1
// 3
// 2

当然,异步依然改变不了它‘单线程’的初心,这一切都是 eventLoop 的功劳。

有时候突发奇想,如何在不改变代码顺序的情况下,使之输出 1、2、3 呢?首先必然是await,然而await会向上传染,如果别人也使用了这个模块,就糟糕了。

或者像下面这样?

let isReturn = false
console.log(1)
Promise.resolve()
  .then(() => {
    isReturn = true
    console.log(2)
  })

while(!isReturn) {

}

console.log(3)

好嘛,直接卡死!

deAsync.js

var deasync = require('deasync');
let isReturn = false
console.log(1)
Promise.resolve()
  .then(() => {
    isReturn = true
    console.log(2)
  })

while(!isReturn) {
  deasync.runLoopOnce()
}

console.log(3)
// 1
// 2
// 3

关键就是deasync.runLoopOnce(),它会强制 node 运行一次事件循环。IMBA!