虽然维护事件队列也需要成本,再由于NodeJS是单线程,事件队列越长,得到响应的时间就越长,并发量上去还是会力不从心。
RESTful API是NodeJS最理想的应用场景,可以处理数万条连接,本身没有太多的逻辑,只需要请求API,组织数据进行返回即可。
6. 实例
看一个具体实例:
console.log('1')
setTimeout(function() {
console.log('2')
new Promise(function(resolve) {
console.log('4')
resolve()
}).then(function() {
console.log('5')
})
setTimeout(() => {
console.log('haha')
})
new Promise(function(resolve) {
console.log('6')
resolve()
}).then(function() {
console.log('66')
})
})
setTimeout(function() {
console.log('hehe')
}, 0)
new Promise(function(resolve) {
console.log('7')
resolve()
}).then(function() {
console.log('8')
})
setTimeout(function() {
console.log('9')
new Promise(function(resolve) {
console.log('11')
resolve()
}).then(function() {
console.log('12')
})
})
new Promise(function(resolve) {
console.log('13')
resolve()
}).then(function() {
console.log('14')
})
// node1 : 1,7,13,8,14,2,4,6,hehe,9,11,5,66,12,haha // 结果不稳定
// node2 : 1,7,13,8,14,2,4,6,hehe,5,66,9,11,12,haha // 结果不稳定
// node3 : 1,7,13,8,14,2,4,6,5,66,hehe,9,11,12,haha // 结果不稳定
// chrome : 1,7,13,8,14,2,4,6,5,66,hehe,9,11,12,haha
chrome的运行比较稳定,而node环境下运行不稳定,可能会出现两种情况。
chrome运行的结果的原因是Promise、process.nextTick()的微任务Event Queue运行的权限比普通宏任务Event Queue权限高,如果取事件队列中的事件的时候有微任务,就先执行微任务队列里的任务,除非该任务在下一轮的Event Loop中,微任务队列清空了之后再执行宏任务队列里的任务。
