Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronously wait for Promise in node REPL

If I start a node REPL and call a function that returns a promise, the function (obviously) returns immediately and some information about the promise is displayed in the console:

$> node
> var foo = () => new Promise((resolve, reject) => setTimeout(resolve('yay'), 1000));
undefined
> foo().then(console.log)
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }

Is there any way I can get node to wait, synchronously, for the promise to resolve (or reject) so that I can get the result printed to the console?


I've seen questions like this one but the solutions there all suggest tacking on a .then() call to do what I want with the result (e.g. log it). However, that doesn't seem to work - note that I already have that in my example, but I never get any log output, so I need some other mechanism to keep the process spinning for long enough that I get to see the output (the string 'yay' in the example).

like image 627
Tomas Aschan Avatar asked Dec 04 '25 07:12

Tomas Aschan


1 Answers

Actually, there's a bug in the example above. You're resolving the promise immediately, so setTimeout doesn't do anything. If you change that line to be

var foo = () => new Promise((resolve, reject) => setTimeout(() => resolve('yay'), 1000));

then the behavior becomes as you describe:

> var foo = () => new Promise((resolve, reject) => setTimeout(() => resolve('yay'), 1000));
undefined
> foo()
Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }

To resolve this, you can use async/await to wrap foo, like this:

> var bar = async () => {
... var res = await foo();
... console.log(res);
... }

Running bar will now let you print (or inspect) the result as you expect:

> bar()
Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
> yay

The last line is printed after a second, unlike when you call foo directly.

like image 120
Johan Persson Avatar answered Dec 05 '25 20:12

Johan Persson