SlideShare a Scribd company logo
1 of 24
Download to read offline
@NicoloRibaudo
Synchronously call your
async functions
NICOLÒ RIBAUDO
@nicolo-ribaudo
@NicoloRibaudo hello@nicr.dev
@NicoloRibaudo 2
NICOLÒ RIBAUDO
● Working at Igalia on web standards
● Maintaining Babel, the JavaScript compiler
nribaudo@igalia.com
@NicoloRibaudo
@nicolo-ribaudo
@nic@tech.lgbt
@nicolo-ribaudo:matrix.org
@NicoloRibaudo
Why would you want to
do it???
3
@NicoloRibaudo
This is bad, don't do it!
4
* unless you need to do it
*
@NicoloRibaudo
Why would you want to do it???
● 2021–2023 — We migrated Babel from internally using
CommonJS to using ESM.
5
🥳
@NicoloRibaudo
Why would you want to do it???
● Babel supports loading external plugins (actually,
everything is a plugin)
6
// babel.config.json
{
"plugins": [
"@babel/plugin-proposal-decorators"
]
}
// Somewhere inside Babel (previously)
function loadAllPlugins() {
const plugin = require(pluginName);
}
// Somewhere inside Babel (now)
async function loadAllPlugins() {
const plugin = await import(pluginName);
}
@NicoloRibaudo
Why would you want to do it???
● async/await virally makes everything asynchronous
7
// Someone using Babel (previously)
import * as babel from "@babel/core";
const code = babel.transform(input, {
// ... config
});
// Someone using Babel (now)
import * as babel from "@babel/core";
const code = await babel.transform(input, {
// ... config
});
@NicoloRibaudo
Why would you want to do it???
● Sometimes you can force😇 asynchronous APIs on
your users — sometimes you can't.
8
@babel/eslint-parser is an ESLint parser to support experimental syntax;
@babel/register hooks into Node.js' require() to compile files on-the-fly.
@NicoloRibaudo
Worker and Atomics
9
@NicoloRibaudo
Worker and Atomics
10
@NicoloRibaudo
Worker and Atomics
11
JavaScript is a multi-threaded programming language:
- new Worker() to spawn multiple threads
- new SharedArrayBuffer() to share memory across
threads
- Atomics.* for thread-safe operations on shared
memory
Atomics.add, Atomics.xor, Atomics.store, Atomics.load,
Atomics.wait, Atomics.notify, Atomics.isLockFree, ...
@NicoloRibaudo
Worker and Atomics
Main thread
function doSomethingSync() {
● Setup a synchronization channel
● Wait until the worker is done
● Read the received result
}
12
Worker thread
addListener("message", () => {
● Asynchronously computer the
result
● Notify the main thread that the
result is ready
});
Send the result back to
the main thread
Share some data and the
synchronization channel with the
worker
@NicoloRibaudo
Worker and Atomics
Main thread
function doSomethingSync() {
const signal = new Int32Array(new SharedArrayBuffer(4));
const { port1, port2 } = new MessageChannel();
// sleep
Atomics.wait(signal, 0, 0);
const { result } = receiveMessageOnPort(port2);
return result;
}
13
Worker thread
addListener("message", () => {
let result =
await doSomethingAsync();
port1.postMessage({ result });
Atomics.notify(signal, 0);
});
signal, port1
{ payload: /* ... */ }
{ result: /* ... */ }
@NicoloRibaudo
Worker and Atomics
Main thread
1. Create the worker
const { Worker, SHARE_ENV } = require("worker_threads");
const worker = new Worker("./path/to/worker.js", {
env: SHARE_ENV,
});
14
@NicoloRibaudo
Worker and Atomics
Main thread, doSomethingSync
2. Delegate the task to the worker
const { MessageChannel } = require("worker_threads");
const signal = new Int32Array(new SharedArrayBuffer(4));
const { port1, port2 } = new MessageChannel();
worker.postMessage({ signal, port: port1, payload }, [port1]);
Atomics.wait(signal, 0, 0);
15
@NicoloRibaudo
Worker and Atomics
Worker thread, "message" listener
3. Perform the task and send the result to the main thread
const result = await doSomethingAsync();
port.postMessage({ result });
port.close();
Atomics.notify(signal, 0);
16
@NicoloRibaudo
Worker and Atomics
Main thread, doSomethingSync
4. After waking up, read the result and return it
const { receiveMessageOnPort } = require("worker_threads");
... const { port1, port2 } = new MessageChannel(); ...
... Atomics.wait(signal, 0, 0); ...
const { result } = receiveMessageOnPort(port2);
return result;
17
@NicoloRibaudo
Production code? Error handling
18
In case of an error, we
must manually report it
to the main thread.
@NicoloRibaudo
Usage outside of
Node.js
19
@NicoloRibaudo
Usage outside of Node.js
20
● In web browsers, the main thread cannot sleep. You can only
synchronously call your asynchronous functions from other web workers.
● receiveMessageOnPort is only available in Node.js. When using
browsers or browser-compatible engines, you need to manually serialize
your data on a SharedArrayBuffer, and synchronously read and
deserialize them on the other side when it wakes up.
@NicoloRibaudo
Who's doing this?
21
@NicoloRibaudo
Who's doing this?
22
● Babel, in @babel/register and @babel/eslint-plugin
● Prettier, in @prettier/sync
● Node.js 20+ itself, to support synchronous import.meta.resolve while
moving ESM loader hooks to a separate thread (nodejs/node#44710)
@NicoloRibaudo
Thank you!
23
And remember to financially support
the open source libraries you are using
😘
Luca Casonato wants me to
explicitly say "Babel" here
@NicoloRibaudo
Worker and Atomics
24
More details:
https://giuseppegurgone.com/synchronizing-async-functions

More Related Content

Similar to Synchronously call your async functions

Cansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_Compromised
Cansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_CompromisedCansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_Compromised
Cansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_CompromisedLiang Chen
 
Metasepi team meeting #6: "Snatch-driven development"
Metasepi team meeting #6: "Snatch-driven development"Metasepi team meeting #6: "Snatch-driven development"
Metasepi team meeting #6: "Snatch-driven development"Kiwamu Okabe
 
From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...Jérôme Petazzoni
 
Browser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmBrowser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmJameel Nabbo
 
Statically Compiling Ruby with LLVM
Statically Compiling Ruby with LLVMStatically Compiling Ruby with LLVM
Statically Compiling Ruby with LLVMLaurent Sansonetti
 
Common mistakes in android development
Common mistakes in android developmentCommon mistakes in android development
Common mistakes in android developmentHoang Nguyen Huu
 
Devoxx 2015 - Building the Internet of Things with Eclipse IoT
Devoxx 2015 - Building the Internet of Things with Eclipse IoTDevoxx 2015 - Building the Internet of Things with Eclipse IoT
Devoxx 2015 - Building the Internet of Things with Eclipse IoTBenjamin Cabé
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.jsPrabin Silwal
 
Helidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxHelidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxDmitry Kornilov
 
Yet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa CommunicationYet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa CommunicationNao Tokui
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...Andrey Karpov
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
04 android
04 android04 android
04 androidguru472
 
Performance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core ArchitecturesPerformance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core ArchitecturesDr. Fabio Baruffa
 

Similar to Synchronously call your async functions (20)

Cansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_Compromised
Cansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_CompromisedCansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_Compromised
Cansecwest_16_Dont_Trust_Your_Eye_Apple_Graphics_Is_Compromised
 
Hack Rio/OS
Hack Rio/OSHack Rio/OS
Hack Rio/OS
 
Metasepi team meeting #6: "Snatch-driven development"
Metasepi team meeting #6: "Snatch-driven development"Metasepi team meeting #6: "Snatch-driven development"
Metasepi team meeting #6: "Snatch-driven development"
 
From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...
 
Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
 
Browser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholmBrowser exploitation SEC-T 2019 stockholm
Browser exploitation SEC-T 2019 stockholm
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Statically Compiling Ruby with LLVM
Statically Compiling Ruby with LLVMStatically Compiling Ruby with LLVM
Statically Compiling Ruby with LLVM
 
Sniffing Mach Messages
Sniffing Mach MessagesSniffing Mach Messages
Sniffing Mach Messages
 
Common mistakes in android development
Common mistakes in android developmentCommon mistakes in android development
Common mistakes in android development
 
Devoxx 2015 - Building the Internet of Things with Eclipse IoT
Devoxx 2015 - Building the Internet of Things with Eclipse IoTDevoxx 2015 - Building the Internet of Things with Eclipse IoT
Devoxx 2015 - Building the Internet of Things with Eclipse IoT
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
Helidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxHelidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptx
 
Yet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa CommunicationYet Another Max/MSP-Cocoa Communication
Yet Another Max/MSP-Cocoa Communication
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
04 android
04 android04 android
04 android
 
Macruby intro
Macruby introMacruby intro
Macruby intro
 
Performance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core ArchitecturesPerformance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core Architectures
 

More from Igalia

Building End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEBuilding End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEIgalia
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesAutomated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesIgalia
 
Embedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to MaintenanceEmbedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to MaintenanceIgalia
 
Optimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfOptimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfIgalia
 
Running JS via WASM faster with JIT
Running JS via WASM      faster with JITRunning JS via WASM      faster with JIT
Running JS via WASM faster with JITIgalia
 
To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!Igalia
 
Implementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamerImplementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamerIgalia
 
8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in MesaIgalia
 
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIntroducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIgalia
 
2023 in Chimera Linux
2023 in Chimera                    Linux2023 in Chimera                    Linux
2023 in Chimera LinuxIgalia
 
Building a Linux distro with LLVM
Building a Linux distro        with LLVMBuilding a Linux distro        with LLVM
Building a Linux distro with LLVMIgalia
 
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUsturnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUsIgalia
 
Graphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devicesGraphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devicesIgalia
 
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOSDelegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOSIgalia
 
MessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the webMessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the webIgalia
 
Replacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shadersReplacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shadersIgalia
 
I'm not an AMD expert, but...
I'm not an AMD expert, but...I'm not an AMD expert, but...
I'm not an AMD expert, but...Igalia
 
Status of Vulkan on Raspberry
Status of Vulkan on RaspberryStatus of Vulkan on Raspberry
Status of Vulkan on RaspberryIgalia
 
Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...Igalia
 

More from Igalia (20)

Building End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEBuilding End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPE
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesAutomated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded Devices
 
Embedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to MaintenanceEmbedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to Maintenance
 
Optimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfOptimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdf
 
Running JS via WASM faster with JIT
Running JS via WASM      faster with JITRunning JS via WASM      faster with JIT
Running JS via WASM faster with JIT
 
To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!
 
Implementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamerImplementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamer
 
8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa
 
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIntroducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
 
2023 in Chimera Linux
2023 in Chimera                    Linux2023 in Chimera                    Linux
2023 in Chimera Linux
 
Building a Linux distro with LLVM
Building a Linux distro        with LLVMBuilding a Linux distro        with LLVM
Building a Linux distro with LLVM
 
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUsturnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
 
Graphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devicesGraphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devices
 
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOSDelegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
 
MessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the webMessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the web
 
Replacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shadersReplacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shaders
 
I'm not an AMD expert, but...
I'm not an AMD expert, but...I'm not an AMD expert, but...
I'm not an AMD expert, but...
 
Status of Vulkan on Raspberry
Status of Vulkan on RaspberryStatus of Vulkan on Raspberry
Status of Vulkan on Raspberry
 
Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...
 

Recently uploaded

Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...akbard9823
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一3sw2qly1
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewingbigorange77
 

Recently uploaded (20)

Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewing
 

Synchronously call your async functions

  • 1. @NicoloRibaudo Synchronously call your async functions NICOLÒ RIBAUDO @nicolo-ribaudo @NicoloRibaudo hello@nicr.dev
  • 2. @NicoloRibaudo 2 NICOLÒ RIBAUDO ● Working at Igalia on web standards ● Maintaining Babel, the JavaScript compiler nribaudo@igalia.com @NicoloRibaudo @nicolo-ribaudo @nic@tech.lgbt @nicolo-ribaudo:matrix.org
  • 3. @NicoloRibaudo Why would you want to do it??? 3
  • 4. @NicoloRibaudo This is bad, don't do it! 4 * unless you need to do it *
  • 5. @NicoloRibaudo Why would you want to do it??? ● 2021–2023 — We migrated Babel from internally using CommonJS to using ESM. 5 🥳
  • 6. @NicoloRibaudo Why would you want to do it??? ● Babel supports loading external plugins (actually, everything is a plugin) 6 // babel.config.json { "plugins": [ "@babel/plugin-proposal-decorators" ] } // Somewhere inside Babel (previously) function loadAllPlugins() { const plugin = require(pluginName); } // Somewhere inside Babel (now) async function loadAllPlugins() { const plugin = await import(pluginName); }
  • 7. @NicoloRibaudo Why would you want to do it??? ● async/await virally makes everything asynchronous 7 // Someone using Babel (previously) import * as babel from "@babel/core"; const code = babel.transform(input, { // ... config }); // Someone using Babel (now) import * as babel from "@babel/core"; const code = await babel.transform(input, { // ... config });
  • 8. @NicoloRibaudo Why would you want to do it??? ● Sometimes you can force😇 asynchronous APIs on your users — sometimes you can't. 8 @babel/eslint-parser is an ESLint parser to support experimental syntax; @babel/register hooks into Node.js' require() to compile files on-the-fly.
  • 11. @NicoloRibaudo Worker and Atomics 11 JavaScript is a multi-threaded programming language: - new Worker() to spawn multiple threads - new SharedArrayBuffer() to share memory across threads - Atomics.* for thread-safe operations on shared memory Atomics.add, Atomics.xor, Atomics.store, Atomics.load, Atomics.wait, Atomics.notify, Atomics.isLockFree, ...
  • 12. @NicoloRibaudo Worker and Atomics Main thread function doSomethingSync() { ● Setup a synchronization channel ● Wait until the worker is done ● Read the received result } 12 Worker thread addListener("message", () => { ● Asynchronously computer the result ● Notify the main thread that the result is ready }); Send the result back to the main thread Share some data and the synchronization channel with the worker
  • 13. @NicoloRibaudo Worker and Atomics Main thread function doSomethingSync() { const signal = new Int32Array(new SharedArrayBuffer(4)); const { port1, port2 } = new MessageChannel(); // sleep Atomics.wait(signal, 0, 0); const { result } = receiveMessageOnPort(port2); return result; } 13 Worker thread addListener("message", () => { let result = await doSomethingAsync(); port1.postMessage({ result }); Atomics.notify(signal, 0); }); signal, port1 { payload: /* ... */ } { result: /* ... */ }
  • 14. @NicoloRibaudo Worker and Atomics Main thread 1. Create the worker const { Worker, SHARE_ENV } = require("worker_threads"); const worker = new Worker("./path/to/worker.js", { env: SHARE_ENV, }); 14
  • 15. @NicoloRibaudo Worker and Atomics Main thread, doSomethingSync 2. Delegate the task to the worker const { MessageChannel } = require("worker_threads"); const signal = new Int32Array(new SharedArrayBuffer(4)); const { port1, port2 } = new MessageChannel(); worker.postMessage({ signal, port: port1, payload }, [port1]); Atomics.wait(signal, 0, 0); 15
  • 16. @NicoloRibaudo Worker and Atomics Worker thread, "message" listener 3. Perform the task and send the result to the main thread const result = await doSomethingAsync(); port.postMessage({ result }); port.close(); Atomics.notify(signal, 0); 16
  • 17. @NicoloRibaudo Worker and Atomics Main thread, doSomethingSync 4. After waking up, read the result and return it const { receiveMessageOnPort } = require("worker_threads"); ... const { port1, port2 } = new MessageChannel(); ... ... Atomics.wait(signal, 0, 0); ... const { result } = receiveMessageOnPort(port2); return result; 17
  • 18. @NicoloRibaudo Production code? Error handling 18 In case of an error, we must manually report it to the main thread.
  • 20. @NicoloRibaudo Usage outside of Node.js 20 ● In web browsers, the main thread cannot sleep. You can only synchronously call your asynchronous functions from other web workers. ● receiveMessageOnPort is only available in Node.js. When using browsers or browser-compatible engines, you need to manually serialize your data on a SharedArrayBuffer, and synchronously read and deserialize them on the other side when it wakes up.
  • 22. @NicoloRibaudo Who's doing this? 22 ● Babel, in @babel/register and @babel/eslint-plugin ● Prettier, in @prettier/sync ● Node.js 20+ itself, to support synchronous import.meta.resolve while moving ESM loader hooks to a separate thread (nodejs/node#44710)
  • 23. @NicoloRibaudo Thank you! 23 And remember to financially support the open source libraries you are using 😘 Luca Casonato wants me to explicitly say "Babel" here
  • 24. @NicoloRibaudo Worker and Atomics 24 More details: https://giuseppegurgone.com/synchronizing-async-functions