Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node repl with async await

I would like to add support to async/await to node repl

Following this issue: https://github.com/nodejs/node/issues/8382

I've tried to use this one https://github.com/paulserraino/babel-repl but it is missing async await suppport

I would like to use this snippet

const awaitMatcher = /^(?:\s*(?:(?:let|var|const)\s)?\s*([^=]+)=\s*|^\s*)(await\s[\s\S]*)/; const asyncWrapper = (code, binder) => {   let assign = binder ? `root.${binder} = ` : '';   return `(function(){ async function _wrap() { return ${assign}${code} } return _wrap();})()`; };  // match & transform const match = input.match(awaitMatcher); if(match) {   input = `${asyncWrapper(match[2], match[1])}`; } 

How can I add this snippet to a custom eval on node repl?

Example in node repl:

> const user = await User.findOne(); 
like image 613
Sibelius Seraphini Avatar asked Jan 05 '17 12:01

Sibelius Seraphini


2 Answers

As of node ^10, you can use the following flag when starting the repl:

node --experimental-repl-await $ await myPromise() 
like image 57
Paul Razvan Berg Avatar answered Oct 02 '22 12:10

Paul Razvan Berg


There is the project https://github.com/ef4/async-repl:

$ async-repl async> 1 + 2 3 async> 1 + await new Promise(r => setTimeout(() => r(2), 1000)) 3 async> let x = 1 + await new Promise(r => setTimeout(() => r(2), 1000)) undefined async> x 3 async> 

Another option, slightly onerous to start but with a great UI, is to use the Chrome Devtools:

$ node --inspect -r esm Debugger listening on ws://127.0.0.1:9229/b4fb341e-da9d-4276-986a-46bb81bdd989 For help see https://nodejs.org/en/docs/inspector > Debugger attached. 

(I am using the esm package here to allow Node to parse import statements.)

Then you go to chrome://inspect in Chrome and you will be able to connect to the node instance. Chrome Devtools has top-level await, great tab-completion etc.

like image 21
w00t Avatar answered Oct 02 '22 11:10

w00t