Dhaval
Dhaval

Reputation: 1436

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?

Upvotes: 4

Views: 1547

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40434

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:

Upvotes: 4

BentoumiTech
BentoumiTech

Reputation: 1683

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

Upvotes: 3

Related Questions