NodeJs 似乎可以毫无错误地中断功能

NodeJs seems to interrupt funciton without error

我有一个 node.js 函数,它的行为方式我无法解释。好像只是停在中间,既不成功也不失败。

我是编码方面的老手,但对 node.js 还是个新手,所以如果有人能向我解释这里发生了什么,我将不胜感激。

我的理解是,如果一个人等待一个承诺,那么迟早会得到一个 return 值(即使它是未定义的),或者如果承诺失败则抛出一个错误。

我也尝试过将 .then 和 .catch 附加到 promise,结果完全相同。

据我所知,这种行为应该是不可能的,调用后的 console.log 中至少有一个应该以某种方式触发。

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');
}; 

问题可能与您实现 problematicFunctionSupposedToReturnPromise 的方式有关,因为这在节点上运行良好:

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. 当每个promise一个接一个堆叠时,Try promise将被打印100次,然后才被执行。此时只有myFunction执行了100次

  2. 当到达同步作用域的末尾时,打印 "will call promises"

  3. 100 个 promises 被拆开,100 个 "got response", "ok" 被打印出来。

您还可以获得更“同步”的工作流程,等待 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()