Q1:async/await和同步调用的区别?
比如我在一段代码中使用了await fs.readFileWithPromise(),这和直接使用fs.readFileSync()在效果上有什么区别?
Q2:redis的pub/sub机制和node创建的web服务器监听端口从而触发事件有什么区别?
//redis的例子
redis.subscribe('sleep');
redis.on('message', async (channel, msg) => {
console.log(msg);
await sleep(3000);
console.log('end');
});
const sleep = ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
上面这个例子,我在另一个地方向sleep这个频道多次pub消息的时候,并不会阻塞,都能即时地打印出msg; 但是下面这个http服务器表现不同:
const http = require('http');
http.createServer(async (req, res) => {
if (req.url === '/favicon.ico') return;
if (req.url === '/') {
console.log('index');
await sleep(3000);
res.end('index');
}
if (req.url === '/test') {
console.log('test');
await sleep(3000);
res.end('test');
}
}).listen(3333);
当我请求'/'时,在我没有得到响应之前,其他对'/'的请求都会被挂起(服务端不打印'index'),但此时对'/test'的请求却能进入(打印'test'),为什么?如果线程被阻塞,那么应该都被挂起;如果没被阻塞,那么其他对'/'的请求为什么会被挂起?
最好能详细说一下它们在node中的执行流程(Event Loop层面)。 先在此谢过~~