Last active
November 29, 2021 11:16
-
-
Save joepie91/dc67316d2a22f321d1a1 to your computer and use it in GitHub Desktop.
PHP vs Node.js: Synchronous vs Asynchronous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log("Before the first file is read."); | |
hypotheticalFileGetContents("sample.txt", function(fileContents){ | |
// fileContents now contains the file contents, this function is only called when the file read in the background has finished | |
console.log("After the first file has completed reading."); | |
}); | |
// You've now told it to start the first read, but it won't 'block' your script execution. It will do the read in the background, and immediately move on with the rest of your code. | |
console.log("Before the second file is read."); | |
hypotheticalFileGetContents("sample2.txt", function(fileContents){ | |
// fileContents now contains the file contents, this function is only called when the file read in the background has finished | |
console.log("After the second file has completed reading."); | |
}); | |
/* Output could look something like this: | |
Before the first file is read. | |
Before the second file is read. | |
After the first file has completed reading. | |
After the second file has completed reading. | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo("Before the first file is read."); | |
$fileContents = file_get_contents("sample.txt"); // You can't do anything while the file is being read, your script is 'stuck'. | |
echo("After the first file has completed reading."); | |
echo("Before the second file is read."); | |
$fileContents = file_get_contents("sample2.txt"); // You can't do anything while the file is being read, your script is 'stuck'. | |
echo("After the second file has completed reading."); | |
/* Output always looks like this: | |
Before the first file is read. | |
After the first file has completed reading. | |
Before the second file is read. | |
After the second file has completed reading. | |
*/ |
Thank You. It really helps to sort out the difference between Synchronous vs Asynchronous.
👍 Thanks Bro, you've turned on the light on Synchronous vs Asynchronous.
Thanks Joep, this was a good refresher! Hi from Netherlands :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this. It really helped with my understanding.