我对 Node.js 很陌生,对 javascript 也比较陌生。我已经了解回调的工作原理并想自己尝试一个功能。这是我的代码:
MyScript.js:
var calledfunction = function()
{
console.log("This is a called function");
for(i=0;i<1090660;i++)
{
console.log(i);
}
console.log('done');
};
var sayHello = require('./sayhello.js');
objhello = new sayHello();
objhello.setupSuite(1,calledfunction);
console.log('Next statement;');
sayhello.js
var _ = require('underscore');
module.exports = exports = CLITEST;
function CLITEST(param1,param2)
{
}
_.extend(CLITEST.prototype, {
setupSuite: function (here,callback) {
console.log(here);
console.log('This is a callback function');
callback();
}
})
上面的程序是通过执行>node Myscript.js来运行的
我的问题是:for循环花费50秒来执行并打印控制台中的所有数字,然后只执行回调函数之外的“Next statements”行。
为什么会发生这种情况?因为我读到的理论说立即执行的语句将被执行,而不必等待函数执行。
理想的输出应该是:打印“下一个语句”,然后打印 for 循环的内容
但在上述情况下,反之亦然?
最佳答案
这不是真正的回调,而是简单的函数调用。函数调用显然是同步的,因为以下语句可能依赖于它们的返回值。
为了使回调异步,您可以使用:setTimeout
或setImmediate
,取决于实际用例。
关于javascript - Node.js 中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22042082/