【问题标题】:Await without Async in deno framwork在 deno 框架中等待没有异步
【发布时间】:2020-05-15 19:34:43
【问题描述】:

Deno 刚刚发布v1.0

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

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 循环,则等待没有异步。

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

【问题讨论】:

    标签: deno


    【解决方案1】:

    Deno 支持top-level await,目前处于第 3 阶段。

    顶级 await 使模块能够充当大型异步函数:使用 顶级等待,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 循环,则等待没有异步。

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

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

    上面的sn-p还是会报错。


    参考资料:

    【讨论】:

      【解决方案2】:

      Deno 实现了顶级等待。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 2021-04-15
        • 2015-09-28
        • 1970-01-01
        • 2013-03-08
        • 2012-08-12
        相关资源
        最近更新 更多