2

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?

Maciej
  • 43
  • 1
  • 5
  • 1
    put some code in .then? - although, the `end` will always log immediately, so perhaps put at least `myPromisse.then(console.log).catch(console.error);` so you can SEE what's happening – Jaromanda X Mar 01 '18 at 08:16

3 Answers3

3

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.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    "The script will not actually exit" Are you sure? I think it does, at least in 2021. I think you didn't try this in practise, or something's changed? -1 therefore – akauppi Apr 23 '21 at 17:59
1

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');
  }
})()
t.kuriyama
  • 167
  • 5
  • 1
    Yes you can, but isn't it unrelated to what the question is about. In my understanding, your code still exits before the promise is completed. – akauppi Apr 23 '21 at 18:00
0

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.

akauppi
  • 17,018
  • 15
  • 95
  • 120