I am new to Deno. In my first step to build Deno simple HTTP server, I saw this on the documentation, It works pretty well:
const server = Deno.listen({ port: 80 })
for await (const conn of server) {
/* etc... */
}
Why Deno documentation prefer for await of
syntax to listen such connections.
Is there any alternative to this? Is this the only way to handle Deno.Conn
from Deno.listen()
? Or just a preferred way?
CodePudding user response:
It's just a pattern, and you're going to see it more in future TypeScript/JavaScript because it is more concise (in most cases). (See end of answer for more.)
This is explained in HTTP Server APIs (low level) | Manual | Deno:
There is also the
.accept()
method on the listener which can be used:const server = Deno.listen({ port: 8080 }); while (true) { try { const conn = await server.accept(); // ... handle the connection ... } catch (err) { // The listener has closed break; } }
Whether using the async iterator or the
.accept()
method, exceptions can be thrown and robust production code should handle these usingtry ... catch
blocks. Especially when it comes to accepting TLS connections, there can be many conditions, like invalid or unknown certificates which can be surfaced on the listener and might need handling in the user code....
And — although it's not directly documented in the manual — you can, of course, also use the standard asyncIterator
:
const server = Deno.listen({ port: 80 });
const iter = server[Symbol.asyncIterator]();
while (true) {
try {
const { done, value: conn } = await iter.next();
if (done) break;
conn;
//^? const conn: Deno.Conn
// ... handle the connection ...
} catch (ex) {
// The listener has closed
break;
}
}
Regarding for await...of
loops: consider the more concise syntax introduced with the for...of
loop compared to the classic for
loop when iterating an array:
const arr = ["foo", "bar", "baz"];
// for loop
for (let i = 0; i < arr.length; i ) {
const item = arr[i];
console.log(item);
}
// for...of loop
for (const item of arr) {
console.log(item);
}
Just like it gave us the opportunity for more concise syntax, so does for await...of
.