简体   繁体   English

NodeJS:从交互式控制台处理承诺

[英]NodeJS: working with promises from an interactive console

I'm learning NodeJS.我正在学习 NodeJS。 One thing I'm finding really annoying is when working with promises from an interactive console while debugging and/or just poking around at the interfaces of various libraries.我发现真正令人讨厌的一件事是在调试和/或只是在各种库的接口上闲逛时使用交互式控制台的承诺。 The work flow is normally;工作流程正常; call some library to do some work, wait for result, poke around at the result to see how it actually behaves and looks like.调用一些库来做一些工作,等待结果,查看结果以查看它的实际行为和外观。

For example (and just for example) I want to interactively inspect the image data structure returned from Jimp .例如(仅举个例子)我想以交互方式检查从Jimp返回的图像数据结构。 I'm finding myself doing this from the console:我发现自己是从控制台执行此操作的:

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 ...

This boiler plate gets annoying to write .. I think I missed a trick.这个锅炉板写起来很烦人..我想我错过了一个技巧。 Is there a more convenient way around this?有没有更方便的方法来解决这个问题? A setting can set, or a library I can load or something?设置可以设置,或者我可以加载的库或其他什么?

I'd rather do this:我宁愿这样做:

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

But this gives "SyntaxError: await is only valid in async function".但这给出了“SyntaxError:await 仅在异步函数中有效”。 Or if not that, then maybe:或者如果不是这样,那么也许:

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

PS "async / await" is not an answer to this question. PS“async/await”不是这个问题的答案。 In order for an async function to be evaluated you have to give control back to the event loop, and you can't do that at an interactive prompt currently AFAIK.为了评估异步函数,您必须将控制权交还给事件循环,并且您无法在当前 AFAIK 的交互式提示下执行此操作

I stumbled on a SO answer for my Q. For node v12+ you can set the --experimental-repl-await option.我偶然发现了 Q 的 SO答案。对于节点 v12+,您可以设置--experimental-repl-await选项。 Was right under my nose all along ... Summary:一直在我的眼皮底下......总结:

Without:没有:

$ 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

With:和:

$ node --experimental-repl-await
Welcome to Node.js v12.18.1.
Type ".help" for more information.
> await Promise.resolve(7)
7

That's what async - await is for.这就是async - await的用途。 It lets you write async code in a way that looks like synchronous code, even though under the hood it is exactly the same as using Promises.它允许您以一种看起来像同步代码的方式编写异步代码,即使在幕后它与使用 Promise 完全相同。 Promises end up being very awkward with all the nesting of functions. Promise 最终会因为函数的所有嵌套而变得非常笨拙。

You can just write:你可以只写:

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

And the only requirement is that the function you do it in has to be declared async.唯一的要求是您执行的函数必须声明为异步。 That means you need at the very least to have one function, you can't use await at the outermost level.这意味着您至少需要拥有一个功能,您不能在最外层使用await

Node.js doesn't really have a way to wait until an event, AFAICT. Node.js 真的没有办法等到事件发生,AFAICT。 But in interactive mode, assuming you waited, all you care about is doing something with the result, so I tried to find convenient ways to get it.但是在交互模式下,假设你在等待,你关心的只是对结果做些什么,所以我试图找到方便的方法来得到它。

The closest I can come up with is some helper like this:我能想到的最接近的是一些这样的帮手:

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

Example usage:用法示例:

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

You still cannot wait for it to finish, but at least the result is available.你仍然不能等待它完成,但至少结果是可用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM