在 deno 框架中等待没有异步

Await without Async in deno framework

Deno 刚刚发布 v1.0.

当我检查 getting started 公会时,我显示了一些不寻常的代码。

import { serve } from "https://deno.land/std@0.50.0/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" });
}

如果您看到 for 循环,则有没有异步的 await。

所以我想知道,javascript async/await 和 deno await 是相同的还是不同的?

Deno 实现顶级 await。

顶级 await 使开发人员能够在异步函数之外使用 await 关键字。它就像一个大的异步函数,导致导入它们的其他模块在开始评估它们的主体之前等待。

来源:https://v8.dev/features/top-level-await

Deno 支持 top-level await,目前处于第 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 允许您使用异步获取的数据初始化模块。

// 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.

请记住,使用 awaitfunction 仍然需要 async 关键字,即使支持 top-level await

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

foo();

上面的代码片段仍然会引发错误。


参考文献: