在面额框架中等待而无需异步

达瓦尔

Deno刚刚发布了v1.0

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

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" });
}

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

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

马科斯·卡萨格兰德

Deno支持top-level await目前处于阶段3的程序。

顶级等待使模块可以充当大型异步功能:使用顶级等待,ECMAScript模块(ESM)可以等待资源,从而导致导入它们的其他模块在开始评估其主体之前等待。

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" }

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

请记住,即使受支持function使用await仍会使用async关键字top-level await

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

foo();

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


参考文献:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章