Maciej
Maciej

Reputation: 43

Waiting for promise in cli

I would like to add an admin user to my node application via CLI. I created a file admin.js. This file looks like:

console.log('start'); 
myPromisse.then().catch(); // This promise add admin to mongodb
console.log('end');

I make node admin and it works ... almost :D Admin is not added because my script is not waiting for the promise. What is the best practice to handle this problem?

Upvotes: 2

Views: 3637

Answers (3)

akauppi
akauppi

Reputation: 18046

None of the answers are correct, I'm afraid. This one is:

Node.js will exit when there are no more callbacks to process. You can use setInterval or setTimeout to always keep one so that the process does not automatically exit.

Upvotes: 0

t.kuriyama
t.kuriyama

Reputation: 177

If Node.js you uses over v7.6.0, you can use async/await syntax.

(async () => {
  console.log('start')

  try {
    const myPromiseResult = await makePromise() // your personal

    // you can write instead of `then` statement below

  } catch (err) {
    console.error(err.message);
  } finally {
    console.log('end');
  }
})()

Upvotes: 1

Terry Lennox
Terry Lennox

Reputation: 30685

I'd do something like:

console.log('start'); 
myPromisse.then(() => {
    console.log('Admin created');
}).catch((err) => {
    console.error('An error occurred creating Admin: ', err);
});

The script will not actually exit until the promise has been resolved or rejected, the last log statement can be misleading in this way.

Upvotes: 3

Related Questions