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

推荐订阅源

F
Full Disclosure
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
Y
Y Combinator Blog
Cloudbric
Cloudbric
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Schneier on Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
Cybersecurity and Infrastructure Security Agency CISA
TaoSecurity Blog
TaoSecurity Blog
Security Latest
Security Latest
N
News and Events Feed by Topic
Hacker News - Newest:
Hacker News - Newest: "LLM"
D
DataBreaches.Net
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Hacker News: Front Page
C
Cisco Blogs
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V
Vulnerabilities – Threatpost
L
LINUX DO - 最新话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
A
About on SuperTechFans
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Jina AI
Jina AI
C
CXSECURITY Database RSS Feed - CXSecurity.com
Schneier on Security
Schneier on Security
T
Tenable Blog
N
News and Events Feed by Topic
W
WeLiveSecurity
有赞技术团队
有赞技术团队
AI
AI
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
T
The Blog of Author Tim Ferriss
S
Security Affairs
Know Your Adversary
Know Your Adversary
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
Google DeepMind News
Google DeepMind News
The Cloudflare 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.