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

NodeJS: working with promises from an interactive console

我正在学习 NodeJS。我发现非常烦人的一件事是在调试 and/or 时使用 交互式控制台 的承诺只是在各种库的接口上闲逛。工作流程正常;调用一些库来做一些工作,等待结果,查看结果以查看它的实际行为和外观。

例如(仅作为示例)我想交互式地检查从 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 is only valid in async function”。或者,如果不是那样,那么也许:

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

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

这就是 async- await 的用途。它允许您以 看起来像 同步代码的方式编写异步代码,即使在幕后它与使用 Promises 完全相同。 Promise 最终会因为函数的所有嵌套而变得非常尴尬。

你可以只写:

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

你还等不及它完成,但至少结果是可用的。

我偶然发现了一个 SO answer for my Q. For node v12+ you can set the --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