Channel Directions in JavaScript
In JavaScript, we don’t have built-in channels like in some other languages. However, we can simulate similar behavior using Promises and async/await. Here’s an example that demonstrates a similar concept:
// This `ping` function returns a Promise that resolves with a message.
// It simulates sending a value through a channel.
function ping(msg) {
return new Promise(resolve => {
setTimeout(() => resolve(msg), 100);
});
}
// The `pong` function accepts a Promise (simulating a receive channel)
// and returns a new Promise (simulating a send channel).
async function pong(pingPromise) {
const msg = await pingPromise;
return new Promise(resolve => {
setTimeout(() => resolve(msg), 100);
});
}
async function main() {
const pingPromise = ping("passed message");
const pongPromise = pong(pingPromise);
console.log(await pongPromise);
}
main();When using Promises as function parameters, you can specify if a Promise is meant to only resolve (send) or be awaited (receive) values. This specificity increases the type-safety of the program when using TypeScript.
The ping function returns a Promise that resolves with a message. It simulates sending a value through a channel.
The pong function accepts one Promise for receiving (pingPromise) and returns a new Promise for sending. It awaits the input Promise and then creates a new Promise that resolves with the received message.
In the main function:
- We create a
pingPromiseby callingping. - We pass this promise to
pong, which returns a newpongPromise. - We await and log the result of
pongPromise.
To run the program:
$ node channel-directions.js
passed messageThis example demonstrates how we can use Promises and async/await in JavaScript to achieve a similar flow to channel directions in other languages. The ping function simulates sending, the pong function simulates receiving and then sending, and the main function orchestrates the flow.