【问题标题】:How can I use await in the NodeJs terminal?如何在 NodeJs 终端中使用 await?
【发布时间】:2020-01-02 20:57:33
【问题描述】:

我经常启动 Node Js 终端来运行小任务或检查一些数据。当前的限制是我不能等待异步函数:

mymachine$ node
> const request = require('request-promise-native')
undefined
> await request('https://google.com')
Thrown:
await request('https://google.com')
^^^^^

SyntaxError: await is only valid in async function

我最终不得不做这样的事情

> let data;
undefined
> request('https://google.com').then(x => data = x)
Promise { <pending> }
> data.length
46262

但是有一些与此相关的不便之处。是否有任何其他替代方法可以在节点终端中链接一系列await 命令?

【问题讨论】:

    标签: javascript node.js terminal


    【解决方案1】:

    以下是在启动 REPL 时无需声明的方法

    function testAsync() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("This executed after 2 sec");
        }, 2000);
      });
    }
    
    let result;
    (async function() {
      result = await testAsync();
      console.log(result);
    })();
    

    【讨论】:

      【解决方案2】:

      通过this site

      Node 版本 10 的 REPL 支持顶级等待 如果您使用 --experimental-repl-await 标志启用它。

      官方文档是here,从版本 13.10.1 起仍然需要命令行开关。

      【讨论】:

      • 这很漂亮。这让我的生活更轻松
      • @Quentin 我们可以使用 IIFE 将 await 包装在 async 中吗?
      • @Noob — 在 REPL 中工作时会非常不方便。
      猜你喜欢
      • 2020-02-05
      • 2018-06-13
      • 2021-09-09
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2018-02-28
      • 1970-01-01
      相关资源
      最近更新 更多