I am trying to learning to asynchronous logic and i have big problems in my head.
I know that almost every function in Node.js is asynchronous. I think our node functions are written this way, so the pointer assignment happens in the event loop. (Node.js up to Posix single-threaded). So event-loop (with help of written asynchronous functions) allows node js to run non-block.
As far as I know, we have to write functions asynchronously.(at least this will be useful).
Question 1: Should we write asynchronously the functions we write in Node.js? Would it be useful if I wrote it?
If so, does it help the event loop? What if we do not write asynchronously? (One function per second or one function per minute)
I learned that a callback should be used. Then I learned just asynchronization can not be achieved using callback (s:code1). Then I learned that nextTick or should use a function like setTimeout. Should we use nexttick yada settimeout in nodejs?
So: code1: it's synchronous
function sum(x, y, cb) {
for (let index = 0; index < 100000000; index++) {}
cb(x + y);
}
console.log(0);
sum(1, 2, cb => {
console.log(cb);
});
console.log(10);
// 0, 3, 10
code2: it's async using (nextTick or setTimeout doesnt matter).
function sum(x, y, cb) {
process.nextTick(() => {
for (let index = 0; index < 100000000; index++) {}
cb(x + y);
});
}
console.log(0);
sum(1, 2, cb => {
console.log(cb);
});
console.log(10);
// 0, 10, 3
Question 2: Different process.nextTick - setTimeOut
exam 1: this is sync
function sum(x, y, callback) {
process.nextTick(() => {
for (let index = 0; index < 10000000000; index++);
callback(x + y);
});
}
var mul = (x, y) =>
new Promise((resolve, reject) => {
resolve(x * y);
});
sum(2, 3, cb => {
console.log(cb);
});
mul(5, 5).then(cb => {
console.log(cb);
});
exam2: it's async
function sum(x, y, callback) {
setTimeout(() => {
for (let index = 0; index < 10000000000; index++);
callback(x + y);
}, 0);
}
var mul = (x, y) =>
new Promise((resolve, reject) => {
resolve(x * y);
});
sum(2, 3, cb => {
console.log(cb);
});
mul(5, 5).then(cb => {
console.log(cb);
});
Why ?
Thank you for the enlightening answers. Can you suggest me any doc or education about this topic.
Thanks.