Files
node/test/parallel/test-net-server-async-iterator.js
Ethan Arrowood 6d8baeabb0 net: add experimental net/promises API
Add an experimental `net/promises` namespace, accessible via
`require('node:net/promises')` or `net.promises`, mirroring the existing
`fs/promises` and `dns/promises` modules.

It provides promise-based variants of net's one-shot lifecycle
operations:

- `connect()` returns a promise that fulfills with a connected Socket
  once the 'connect' event fires, and rejects on connection failure or
  when an optional AbortSignal is aborted, destroying the socket.
- `listen()` creates a server, begins listening, and returns a promise
  that fulfills with the listening Server once the 'listening' event
  fires. It rejects if the server fails to bind or an optional
  AbortSignal is aborted, closing the server.

The functions are named for the actions they await, forming a parallel
`connect()`/`listen()` pair. This is intentionally not the callback
API's factory taxonomy: there `createConnection()` is canonical because
it both creates a socket and initiates connecting, whereas
`createServer()` is a pure factory that does not listen. A
`createConnection`/`createServer` pairing would be inconsistent here
because `createServer` has no completion to await, so no
`createConnection` alias is provided.

Refs: https://github.com/nodejs/node/issues/21482
Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Ethan Arrowood <ethan@arrowood.dev>
PR-URL: https://github.com/nodejs/node/pull/63965
Reviewed-By: Tim Perry <pimterry@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-07-28 19:29:48 +00:00

51 lines
1.2 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
const { once } = require('events');
(async () => {
// `for await...of` yields each incoming connection as a net.Socket.
{
const server = net.createServer().listen(0);
await once(server, 'listening');
const { port } = server.address();
const total = 3;
const clients = [];
for (let i = 0; i < total; i++) {
clients.push(net.connect(port));
}
let count = 0;
for await (const socket of server) {
assert.ok(socket instanceof net.Socket);
socket.end();
if (++count === total) break;
}
assert.strictEqual(count, total);
// Breaking out of the loop stops iterating but does not close the server.
assert.strictEqual(server.listening, true);
server.close();
for (const client of clients) {
client.destroy();
}
}
// Iteration ends cleanly when the server closes.
{
const server = net.createServer().listen(0);
await once(server, 'listening');
process.nextTick(() => server.close());
let count = 0;
for await (const socket of server) {
count++;
socket.end();
}
assert.strictEqual(count, 0);
}
})().then(common.mustCall());