I have tryed to find answer on web, and did it partly. But I still can not completely understand how JS can run ansyncronous code?
My seeing of things:
JS give us ability of asyncronous programming. That means that we can start first task, then while one is in progress we can start second task, etc. Before js can start second task it should be freed from the previous task. It can be achived with 2 ways:
- js by its own end the task (the code which should be processed by js only)
- js can start the task which should be processed by filesystem for example. In this case js, do its work, pass the task to filesystem and starts to process other queued tasks. When js is freed and filesystem have returned the result, js can continue that task.
So we can not achive asyncronous by just writing the next code:
function doSth( callback ) {
let arr = [];
for ( let i=1e6; i > 0; i-- )
arr.push( i );
callback();
}
doSth( console.log.bind( null, 'I am callback' );
console.log( 'just a line' );
due to doSth() contains only js's work it will be completed first and then just appear 'just a line'? So it is not asyncronously, right? But if we will have filesystem task insted of loop, we will have asyncronous function?
And one more question: Are promises really asyncronous? How can they be asyncronous (i mean, can other tasks be processed at the time of promise processing), either promises just mimics asyncronous code? *I know, there is additional queue for promises.
Maby I just don't understand some base? I'll be glad if you can explain me to make my questions more explictly for me.