0

Why is there such a sequence in the console:

enter image description here

const crypto = require('crypto');
const https = require('https');
const fs = require('fs');
const startDate = Date.now();
const invokeHttpRequest = () => {
    https.request('https://www.google.com', res => {
        res.on('data', () => {});
        res.on('end', () => {
            console.log('HTTP returns data', Date.now() - startDate)
        });
    })
        .end();
}
const invokeHash = () => {
    crypto.pbkdf2('test', 'test2', 100000, 512, 'sha512' , () => {
        console.log('crypto:', Date.now() - startDate);
    });
}
invokeHttpRequest();
invokeHash();
invokeHash();
invokeHash();
invokeHash();
fs.readFile('index.js', 'utf-8', () => {
    console.log('FS:', Date.now() - startDate);
});

I want to know how the loop works and why is there such a sequence in the console:

  1. HTTP returns data
  2. crypto
  3. FS
  4. crypto
  5. crypto
  6. crypto

Why exactly did FS skip crypto and take the second thread and not the last one

YouJeen
  • 1
  • 1

1 Answers1

0

Node.js is asynchronous, in fact it parralelize task.

Thus, when you call 4 times invokeHash calls are made before readfile, but invokeHash take time to execute and then invokeHash function return after readfile.

If you need to execute readfile after invokeHash calls, you should implement a callback or a promise in invokeHash function. And then execute readfil when all invokeHash function returns.

Alaindeseine
  • 3,260
  • 1
  • 11
  • 21
  • Yes, but why is the console output like this: -HTTP returns data -crypto -FS -crypto -crypto -crypto – YouJeen Mar 17 '22 at 10:19
  • That's exactly what i explain. Your http requestion end before the others, and then console is before the others. Try we a website that is not performant and the console order will change. – Alaindeseine Mar 17 '22 at 10:27