我正在使用 Mocha 测试框架自动化网页,并遇到了术语“同步”和“异步代码”。 当您发送 HTTP 请求时,我熟悉同步和异步事件...但我从未听说过代码是同步和异步的。 任何人都愿意解释一下...我在之前的问题中看到它与回调有关,但即便如此,我仍然对这个概念感到非常困惑。
最佳答案
下面是我的服务器代码的简化版本。我演示了同步代码(在您开始执行操作后,在完成之前不会开始进一步的操作)和异步代码(您开始执行操作,然后继续执行其他操作,并在稍后的某个时刻“回调”或从第一个操作中获取结果。)
这会产生一些重要的后果。几乎每次调用异步函数时:
异步函数的返回值是无用的,因为该函数将立即返回,尽管查找结果需要很长时间。
您必须等到回调函数执行后才能访问结果。
调用异步函数之后的代码行将在异步回调函数运行之前执行。
作为示例,下面代码中 console.logs 的顺序为:
line 3 - before sync
line 8 - after sync, before async
line 16 - after async call, outside callback
line 14 - inside async call and callback
// synchronous operations execute immediately, subsequent code
// doesn't execute until the synchronous operation completes.
console.log('line 3 - before sync');
var app = require('express')();
var cfgFile = require('fs').readFileSync('./config.json');
var cfg = JSON.parse(cfgFile);
var server = require('http').createServer(app);
console.log('line 8 - after sync, before async');
// When you call an asynchronous function, something starts happening,
// and the callback function will be run later:
server.listen(cfg.port, function(){
// Do things that need the http server to be started
console.log('line 14 - inside async call and callback');
});
console.log('line 16 - after async call, outside callback');
关于javascript - 同步与异步 Nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257638/