Why does nodejs wait a long time before exiting

109 Views Asked by At

i try to write a Creation Operator to got a observable from a wsprovider on polkadot.js. and try to got polkadot event.

this is the code

import {from, fromEvent, of,Observable} from 'rxjs';
import {tap,mergeMap} from "rxjs/operators"

import { WsProvider } from '@polkadot/api';

console.time("main")
const urls = of("wss://192")

const fromWs =  (url:string) => {
  const ws = new WsProvider(url,0);
  ws.connect().then(val => console.timeLog("main",val)).catch(console.error)
  return new Observable((subscriber) => {

    ws.on("disconnected",()=>{
      console.timeLog("main","wss disconnected")
      subscriber.next(url);
      subscriber.complete()
    })
    ws.on('error', () =>{
      console.timeLog("main","wss error")
      subscriber.complete()
    })
    ws.on('connected' ,() => {
      console.timeLog("main", `${url} connected`)
    })
    setTimeout(() => {
      console.timeLog("main", `${url} timeout`)
      ws.disconnect().then(val=> console.timeLog("main",'ws disconnect')).catch(err => console.error("disconnect error"))
      subscriber.complete()
    },2000)
  })
}

urls.pipe(
    tap(console.log),
    mergeMap( (url:string) =>{
      return fromWs(url)
    }),
).subscribe({
  next: val => console.timeLog("main", 'subcrnext'),
  error: err=> console.timeLog("main", "sub error"),
  complete: () => console.timeLog("main", "sub complete")
})

process.on('exit', (code) => {
  console.timeLog("main",'System exit');
});


and i try to execute it by ts-node.

➜  rxjsexample ts-node src/main.ts
wss://192
main: 11.959ms undefined
main: 2.013s wss://192 timeout
main: 2.015s wss error
main: 2.016s sub complete
main: 2.017s wss disconnected
main: 2.018s ws disconnect
main: 2:10.176 (m:ss.mmm) System exit

at 2.018s, the network conenct is disconnect. but at 2m10s, the nodejs just exits.

What is nodejs doing during this time?

1

There are 1 best solutions below

3
tmarwen On

The short answer is a lot.

node.js is an event-loop based runtime which goes through a set of prefixed phases at each loop.

Once your timer function is executed, there should be no more event providers (timers, I/O...) and the runtime will go through a cleanup phase executing any close event handlers along with the process#exit event.

Hence between the timer function execution and the internal checking / cleanup, there still statements to execute which will lead to the time laps you are seeing between the last userland timer function and the last userland exit event handler.