4

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?

2 Answers 2

4

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:

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.