|
| 1 | +//example where pending callbacks are scheduled in a different phase. |
| 2 | +const net = require('net'); |
| 3 | +const fs = require(`fs`); |
| 4 | + |
| 5 | +console.log(`START`); |
| 6 | +// Define the IP and port |
| 7 | +//change the host to a none existant port host, |
| 8 | +//the ECONNREFUSED will be queued in the pending callbacks phase output will be |
| 9 | +/*START |
| 10 | +END |
| 11 | +time out |
| 12 | +Connection error: connect ECONNREFUSED 127.0.0.1:80 |
| 13 | +Connection closed |
| 14 | +readFileCallback hello world |
| 15 | +*/ |
| 16 | +//but if you change it to a valid ip/port say google's |
| 17 | +//the output will be |
| 18 | +/* |
| 19 | +START |
| 20 | +END |
| 21 | +time out |
| 22 | +readFileCallback hello world |
| 23 | +Connected to server at 142.250.188.23:80 |
| 24 | +*/ |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +// Create a client |
| 29 | +const clientFail = new net.Socket(); |
| 30 | +const clientSuccess = new net.Socket(); |
| 31 | + |
| 32 | +// Connect to the server (fails) |
| 33 | +clientFail.connect(9999,'127.0.0.1', () => { |
| 34 | + console.log(`Connected to server at ${'192.168.4.21'}:${9999}`); |
| 35 | +}); |
| 36 | +// Connect to the server that exists (this is example.com) |
| 37 | +clientSuccess.connect(80, '93.184.215.14', () => { |
| 38 | + console.log(`Connected to server at ${'93.184.215.14'}:${80}`); |
| 39 | +}); |
| 40 | + |
| 41 | +// Handle errors |
| 42 | +clientFail.on('error', (err) => { |
| 43 | + console.error(`Connection error: ${err.message}`); |
| 44 | +}); |
| 45 | +// Handle errors |
| 46 | +clientSuccess.on('error', (err) => { |
| 47 | + console.error(`Connection error: ${err.message}`); |
| 48 | +}); |
| 49 | + |
| 50 | + |
| 51 | +//slow down the initial phase |
| 52 | +for (let i = 1; i <= 500000000; i++); |
| 53 | +//after the loop ends and initial phase is done, we enter the poll phase and actually read the file (no callbacks ready) |
| 54 | +console.log(`END`); |
| 55 | + |
0 commit comments