Goroutines in Logo
On this page
Our example demonstrates the use of 🌐goroutines🌐 for concurrency in JavaScript. In JavaScript, we achieve concurrency using asynchronous functions and promises. Here’s how you can achieve similar functionality in JavaScript:
function f(from) {
for (let i = 0; i < 3; i++) {
console.log(from + ":", i);
}
}
// Calling the function directly and synchronously.
f('direct');
// Using setTimeout to simulate goroutines running concurrently.
setTimeout(() => f('goroutine'), 0);
// Using an immediately invoked function expression (IIFE) to simulate anonymous goroutine.
setTimeout(() => {
(function(msg) {
console.log(msg);
})('going');
}, 0);
// Wait for a second to let all asynchronous operations finish.
setTimeout(() => {
console.log('done');
}, 1000);
Explanation:
Direct Function Call
f('direct');
This is a synchronous call to the function, similar to calling
f(s)
in a traditional way.Simulating Goroutines with
setTimeout
setTimeout(() => f('goroutine'), 0);
JavaScript doesn’t have goroutines, but we can simulate concurrent execution using
setTimeout
, which schedules the function to run after the current call stack is clear.Anonymous Function Call
setTimeout(() => { (function(msg) { console.log(msg); })('going'); }, 0);
This simulates an anonymous function call that runs concurrently.
Waiting for Functions to Complete
setTimeout(() => { console.log('done'); }, 1000);
We use a delay with
setTimeout
to ensure that all asynchronous operations finish before printing “done”.
Running the Program
To run this code, put it in a JavaScript file (e.g., concurrency.js
) and execute it with Node.js:
$ node concurrency.js
Expected Output:
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done
Next, we’ll explore more about handling concurrency in JavaScript with Promises and async/await
.
Note:
JavaScript concurrency is typically handled using its event loop, asynchronous functions, promises, and the newer async/await
syntax. Our example uses setTimeout
to mimic concurrent execution, but for more robust and real-world concurrency control, you would use these modern asynchronous programming features.