NodeJS:使用来自交互式控制台的承诺

我正在学习NodeJS。我发现真正令人烦恼的一件事是在调试和/或随意浏览各种库的接口时使用交互式控制台中的promise。工作流程正常;调用一些库做一些工作,等待结果,在结果周围四处查看,以了解其实际行为和外观。

例如(仅举例来说),我想交互式检查从Jimp返回的图像数据结构。我发现自己是从控制台执行此操作的:

const Jimp = require('jimp');
const fs = require('fs');
let data = fs.readFileSync('path/to/my/test/images')
let image = null
Jimp.read(data).then((result,error) => { image = result; });
// Work with image here ...

这个样板令人讨厌写..我想我错过了一个把戏。有没有更方便的解决方法?可以设置一项设置,或者可以加载一个库吗?

我宁愿这样做:

...
let image = await Jimp.read(data);
// Work with image here ...

但这给出了“ SyntaxError:await仅在异步函数中有效”。否则,也许是这样:

...
let image = resolveMe(Jimp.read(data))
// Work with image here ...

P.S。 “异步/等待”不是此问题的答案。为了评估异步功能,您必须将控制权交还给事件循环,并且您不能在当前AFAIK的 interactive 提示符下执行该操作。

gyz111427 回答:NodeJS:使用来自交互式控制台的承诺

这就是async-await的用途。它可以让您以类似于同步代码的方式编写异步代码,即使在幕后它与使用Promises完全相同。对于所有功能的嵌套,最终它们都变得很尴尬。

您可以编写:

let image = await Jimp.read(data); 
// do something with image

唯一的要求是必须将在其中执行的功能声明为异步。这意味着您至少需要具有一个功能,不能在最外层使用await

,

Node.js确实没有办法等到事件AFAICT。但是在交互模式下,假设您等待了,那么您关心的只是对结果做些什么,因此我试图找到方便的方法来获得它。

我能想到的最接近的是这样的一些帮助器:

Promise.prototype.a = function() {
    this
        .then(res => {
            Promise.res = res;
            console.log("async",res);
        })
        .catch(console.error)
}

用法示例:

Welcome to Node.js v12.2.0.
Type ".help" for more information.
> Promise.prototype.a = function() {
...     this
...         .then(res => {
.....           Promise.res = res;
.....           console.log("async",res);
.....       })
...         .catch(console.error)
... }
[Function]
> 
> function sleep(ms) {
...     return new Promise((resolve) => {
.....       setTimeout(resolve,ms);
.....   });
... }  
undefined
> 
> async function afterSleep(sec) {
...     await sleep(sec * 1000);
...     return 100;
... }
undefined
> afterSleep(2).a()
undefined
> async 100

> Promise.res
100

您仍然不能等待它完成,但是至少可以得到结果。

,

我偶然发现了Q的SO answer。对于节点v12 +,您可以设置--experimental-repl-await选项。一直在我的鼻子底下...摘要:

无:

$ node
Welcome to Node.js v12.18.1.
Type ".help" for more information.
> await Promise.resolve(7)
await Promise.resolve(7)
^^^^^
Uncaught SyntaxError: await is only valid in async function

使用:

$ node --experimental-repl-await
Welcome to Node.js v12.18.1.
Type ".help" for more information.
> await Promise.resolve(7)
7
本文链接:https://www.f2er.com/2714884.html

大家都在问