How to enable promises when using an application with REPL

I have a Node core web server (Koa.js + ORM). I like to start with REPL , which means that I can use my application as a CLI tool.

All my requests return Promises, but I don’t know how I can resolve them in REPL. How can I resolve them?

For example, the following code (fetch () queries the database and returns a promise) gives only this output Promise {_bitField: 4325376, _fulfillmentHandler0: undefined, _rejectionHandler0: undefined …}

Transaction.where('reference', '1').fetch().then((res) => return res)
+2
source share
3 answers

Update: Node.js now does this by default and allows promises


Old answer:

, :

> Transaction.where('reference', '1').fetch().then((res) => out = res)
[Object Promise]
> out
  /* your data outputted here since the global was assigned to*/

await REPL Node, .

+3

( ) , .

, , repl:

// sample-repl.js
const repl=require('repl');
function replEvalPromise(cmd,ctx,filename,cb) {
  let result=eval(cmd);
  if (result instanceof Promise) {
    return result
      .then(response=>cb(null,response));
  }
  return cb(null, result);
}
repl.start({ prompt: 'promise-aware> ', eval: replEvalPromise });

REPL , :

$ node sample-repl.js
promise-aware> new Promise(resolve=>setTimeout(()=>resolve('Finished!'),5000));
'Finished!'
promise-aware> out = new Promise(resolve=>setTimeout(()=>resolve('Finished!'),5000));
'Finished!'
promise-aware> out
'Finished!'
promise-aware>

, .

node REPL :

> out = new Promise(resolve=>setTimeout(()=>resolve('Finished!'),5000));
Promise { <pending> }
> out
Promise { <pending> }
> out
Promise { <pending> }
> out
Promise { <pending> }
> out
Promise { 'Finished!' }
>
+1

Source: https://habr.com/ru/post/1665871/


All Articles