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

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

Mathias Bynens

A horrifying globalThis polyfill in universal JavaScript JavaScript engine fundamentals: optimizing prototypes JavaScript engine fundamentals: Shapes and Inline Caches ECMAScript regular expressions are getting better! Unicode property escapes in JavaScript regular expressions ES2015 const is not about immutability Valid JavaScript variable names in ES2015 Unicode-aware regular expressions in ES2015 Dear Google, please fix plain text emails in Gmail PBKDF2+HMAC hash collisions explained JavaScript has a Unicode problem Processing Content Security Policy violation reports Hiding JSON-formatted data in the DOM with CSP enabled Loading JSON-formatted data with Ajax and xhr.responseType='json' Reserved keywords in JavaScript How to support full Unicode in MySQL databases How to speedrun Dropbox’s Dropquest 2012 Unquoted font family names in CSS Unquoted property names / object keys in JavaScript Valid JavaScript variable names in ES5 CSS character escape sequences JavaScript’s internal character encoding: UCS-2 or UTF-16? The smallest possible valid (X)HTML documents JavaScript character escape sequences JavaScript foo.prototype.bar notation Ambiguous ampersands HTML element + attribute notation How I detect and use localStorage: a simple JavaScript pattern Unquoted attribute values in HTML and CSS/JS selectors The end-tag open (ETAGO) delimiter Using the oninput event handler with onkeyup/onkeydown as its fallback Everything you always wanted to know about touch icons In defense of CSS hacks — introducing “safe CSS hacks” AirPlay video support in iOS Safari — a bookmarklet Completing Dropbox’s Dropquest 2011 in 60 seconds Using CSS without HTML How to create simple Mac apps from shell scripts Using setTimeout to speed up window.onload Bulletproof JavaScript benchmarks Thoughts on Safari Reader’s generated HTML How to enable Safari Reader on your site? The XML serialization of HTML5, aka ‘XHTML5’ The id attribute got more classy in HTML5 The three levels of HTML5 usage The HTML5 document.head DOM tree accessor Bulletproof HTML5 <details> fallback using jQuery Displaying hidden elements like <head> using CSS Inline <script> and <style> vs. external .js and .css — what’s the size threshold? Using Showdown/PageDown with and without jQuery
Asynchronous stack traces: why await beats Promise#then()
Mathias · 2017-09-12 · via Mathias Bynens

Compared to using promises directly, not only can async and await make code more readable for developers — they enable some interesting optimizations in JavaScript engines, too! This write-up is about one such optimization involving stack traces for asynchronous code.

The fundamental difference between await and vanilla promises is that await X() suspends execution of the current function, while promise.then(X) continues execution of the current function after adding the X call to the callback chain. In the context of stack traces, this difference is pretty significant.

When a promise chain (desugared or not) throws an unhandled exception at any point, the JavaScript engine displays an error message and (hopefully) a useful stack trace. As a developer, you expect this regardless of whether you use vanilla promises or async and await.

Vanilla promises

Imagine a scenario where a function c is called when a call to an asynchronous function b resolves:

const a = () => {
	b().then(() => c());
};

When a is called, the following happens synchronously:

  • b is called and returns a promise that will resolve at some point in the future.
  • The .then callback (which is effectively calling c()) is added to the callback chain (or, in V8 lingo: […] is added as a resolve handler).

After that, we’re done executing the code in the body of function a. a is never suspended, and the context is gone by the time the asynchronous call to b resolves. Imagine what happens if b (or c) asynchronously throws an exception. The stack trace should include a, since that’s where b (or c) was called from, right? How is that possible now that we have no reference to a anymore?

To make it work, the JavaScript engine needs to do something in addition to the above steps: it captures and stores the stack trace within a while it still has the chance. In V8, the stack trace is attached to the promise that b returns. When the promise fulfills, the stack trace is passed on so that c can use it as needed.

Capturing the stack trace takes time (i.e. degrades performance); storing these stack traces requires memory.

async/await

Here’s the same program, written using async/await instead of vanilla promises:

const a = async () => {
	await b();
	c();
};

With await, we can restore the call chain even if we do not collect the stack trace at the await call. This is possible because a is suspended, waiting for b to resolve. If b throws an exception, the stack trace can be reconstructed on-demand in this manner. If c throws an exception, the stack trace can be constructed just like it would be for a synchronous function, because we’re still within a when that happens.

Recommendations

Like most ECMAScript features that are seemingly “just syntax sugar”, async/await is more than that.

Enable JavaScript engines to handle stack traces in a more performant and memory-efficient manner by following these recommendations:

  • Prefer async/await over desugared promises.
  • Use @babel/preset-env to avoid transpiling async/await unnecessarily.

Although V8 doesn’t implement this optimization yet, following this advice ensures optimal performance once we (or other JavaScript engines) do.

In general, don’t transpile code unless you absolutely need to! For example, all modern browsers that support service workers also support async/await. Consequently, there is no need to transpile your service worker–specific code down to vanilla promises. The same argument applies to browsers with JavaScript modules support. For more information, see Philip’s blog post on deploying ES2015+ code in production today.