drdeath
drdeath

Reputation: 133

NodeJs seems to interrupt funciton without error

I've got a node.js function that behaves in a way I can't explain. It seems to just stop in the middle and neither succeed nor fail.

I'm an old hand at coding, but rather new to node.js, so I'd be grateful if somebody could explain to me what's going on here.

My understanding is that if one awaits a promise, one sooner or later either gets a return value (even if it's undefined) or an error is thrown if the promise fails.

I've also tried attaching a .then and a .catch to the promise, with exactly the same result.

As far as my understanding goes, this behaviour shoud not be possible, at least one of the console.log after the invocation should trigger one way or another.

for (let i = 0; i < 100; i++) {

    myFunction();

}

const myFunction = async () => {
    try {
        console.log('This triggers 100 times');
        var response = await problematicFunctionSupposedToReturnPromise();
        console.log(response, 'This never triggers');

    } catch (err) {
        console.log(err,'This never triggers either');
    }
    console.log('Nor does this');
}; 

Upvotes: 0

Views: 211

Answers (1)

Peterrabbit
Peterrabbit

Reputation: 2247

The problem might be rather related to the way you have implemented that problematicFunctionSupposedToReturnPromise, because this is working fine with node :

function problematicFunctionSupposedToReturnPromise() {
  return new Promise((resolve, _) => {
    resolve("ok!")
  })
}

const myFunction = async () => {
  console.log('Try promise');
  var response = await problematicFunctionSupposedToReturnPromise()
    .catch(err => console("oops"));
  console.log('Got response', response);
};

for (let i = 0; i < 100; i++) {

  myFunction();

}


console.log("will call promises")
  1. The Try promise will be printed a 100 times all together when each promise is stacked one after another, before being executed. Only myFunction is executed a 100 times at this moment.

  2. When the end of synchronous scope is reached, the "will call promises" is printed

  3. The 100 promises are unstacked and the 100 "got response", "ok" are printed.

You may also obtain a more "synchronous" workflow is you await myFunction

async function promises() {
  function problematicFunctionSupposedToReturnPromise() {
    return new Promise((resolve, _) => {
      resolve("ok!")
    })
  }

  const myFunction = async () => {
    console.log('Try promise');
    var response = await problematicFunctionSupposedToReturnPromise()
      .catch(err => console("oops"));
    console.log('Got response', response);
  };

  for (let i = 0; i < 100; i++) {

    await myFunction();

  }
}

promises()

Upvotes: 1

Related Questions