Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await without Async in deno framework

Deno just released v1.0.

When I was checking getting started guild I show some unusual code.

import { serve } from "https://deno.land/[email protected]/http/server.ts";
const s = serve({ port: 8000 });

console.log("http://localhost:8000/");

for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}

If you see for loop there is await without async.

So I'm wondering, is javascript async/await and deno await both are same or it's different?

like image 418
Dhaval Avatar asked Oct 31 '25 11:10

Dhaval


2 Answers

Deno supports top-level await which is currently on stage 3.

Top-level await enables modules to act as big async functions: With top-level await, ECMAScript Modules (ESM) can await resources, causing other modules who import them to wait before they start evaluating their body.

top-level await allows you to initialize a module with asynchronously fetched data.

// my-module.js
const res = await fetch('https://example.com/some-data');
export default await res.json();
// some module
import data from './my-module.js';
console.log(data); // { "some": "json" }

If you see for loop there is await without async.

Have in mind that functions using await will still need async keyword, even if top-level await is supported.

function foo() { // async is needed
   const res = await fetch('https://example.com/api/json')
   console.log(res);
}

foo();

The above snippet still throws an error.


References:

  • https://github.com/tc39/proposal-top-level-await
  • https://2ality.com/2019/12/top-level-await.html
  • https://v8.dev/features/top-level-await
like image 198
Marcos Casagrande Avatar answered Nov 02 '25 00:11

Marcos Casagrande


Deno implements top-level await.

Top-level await enables developers to use the await keyword outside of async functions. It acts like a big async function causing other modules who import them to wait before they start evaluating their body.

Source: https://v8.dev/features/top-level-await

like image 28
BentoumiTech Avatar answered Nov 02 '25 00:11

BentoumiTech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!