Nodejs如何在完成后再次调用函数

eez*_*eze -1 javascript asynchronous node.js

假设我有一个函数,

function hello(){
  console.log('hello world');
}
Run Code Online (Sandbox Code Playgroud)

现在我想在该函数完成后立即再次调用它。所以我做了这样的事情:

function hello(){
  console.log('hello world');
  hello();
}
Run Code Online (Sandbox Code Playgroud)

然而,这样做并不能按预期工作,因为由于nodejs的异步特性,在执行完成hello之前会再次调用。console.log('hello world');

有没有办法hello重复运行该函数,但等到它完成后再运行第二次?

Pau*_*aul 5

你的问题不在于 JavaScript 的异步特性。相反,你有一个无限的递归,这很快就会导致 aRangeError: Maximum call stack size exceeded来保护你免于通过大量函数调用消耗所有机器内存。

您不需要有停止条件。实际上,您可以使用 JavaScript 的异步特性来修复它:

function hello(){
  console.log('hello world');
  setTimeout(hello, 0);
}

hello();
Run Code Online (Sandbox Code Playgroud)