Search code examples
javascriptnode.jsasync-awaites6-promise

Why does the process end after executing a one function without any errors?


I thought the process was stuck waiting for resolve. But it returned "Hello, A" and process exit.

I can't understand why it just exited.

I know it just solve if i just add resolve or reject.

But i want something deep.

function funA(name) {
  return new Promise(function(resolve, reject) {
    console.log("Hello, " + name);
  });
}

(async() => {
  await funA("A");
  await funA("B");
})();

// Hello, A
// exit

VScode Image


Resolve

what happens when a Promise never resolves?


Solution

  • Make sure to resolve your promise, otherwise it will still wait for FunA("A") to be finished. You can do this by calling resolve():

    function funA(name) {
      return new Promise(function (resolve, reject) {
        console.log("Hello, " + name);
        resolve();
      });
    }
    
    (async () => {
      await funA("A");
      await funA("B");
    })();

    EDIT: to answer your question why it exits and is not pending if you don't resolve: this happens when there are no more callbacks to process by nodejs. When you return your broken pending promise without a resolve, you have not created a callback in the nodejs queue, thus nodejs decided to exit