Skip to content

Commit d93efec

Browse files
author
James Halliday
committed
more asynchrony, less useless function tricks
1 parent c1ff043 commit d93efec

File tree

1 file changed

+40
-33
lines changed

1 file changed

+40
-33
lines changed

javascript.markdown

+40-33
Original file line numberDiff line numberDiff line change
@@ -1059,39 +1059,6 @@ console.log(add(5, 2)); // 7
10591059
When you declare functions in expressions you don't need to
10601060
give them a name.
10611061
1062-
---
1063-
# immediately executing function
1064-
1065-
Because functions can appear in expressions, you can
1066-
immediately execute a function by defining the function
1067-
immediately followed by `(...)` to call the function with
1068-
arguments.
1069-
1070-
``` js
1071-
var sum = function (a, b, c) {
1072-
return a + b + c;
1073-
}(3, 4, 5);
1074-
console.log(sum); // 12
1075-
```
1076-
1077-
Variables declared inside functions are only visible in that
1078-
function, so immediately executing functions are sometimes
1079-
used to create an isolated scope.
1080-
1081-
---
1082-
You could even do:
1083-
1084-
``` js
1085-
console.log(100 + function (a, b, c) {
1086-
return a + b + c;
1087-
}(3, 4, 5) * 2);
1088-
```
1089-
1090-
which is the same as `100 + 12 * 2`, so the program prints:
1091-
1092-
```
1093-
124
1094-
```
10951062
---
10961063
# higher-order functions
10971064
@@ -1216,6 +1183,46 @@ console.log(n.add(5)); // 105
12161183
console.log(n.multiply(3)); // 315
12171184
```
12181185
1186+
---
1187+
# asynchrony
1188+
1189+
Often, javascript APIs make use of callbacks:
1190+
1191+
``` js
1192+
var fs = require('fs');
1193+
fs.readFile('foo.txt', function (err, src0) {
1194+
fs.readFile('bar.txt', function (err, src1) {
1195+
console.log(src0.length + src1.length);
1196+
});
1197+
});
1198+
```
1199+
1200+
---
1201+
# callback order of operations
1202+
1203+
``` js
1204+
console.log(1);
1205+
var fs = require('fs');
1206+
fs.readFile('foo.txt', function (err, src0) {
1207+
console.log(3);
1208+
fs.readFile('bar.txt', function (err, src1) {
1209+
console.log(5);
1210+
console.log(src0.length + src1.length);
1211+
});
1212+
console.log(4);
1213+
});
1214+
console.log(2);
1215+
```
1216+
1217+
prints: 1, 2, 3, 4, 5
1218+
1219+
---
1220+
# the event loop
1221+
1222+
Only after the current block of code has
1223+
"run to completion" do callbacks scheduled
1224+
on the event loop execute.
1225+
12191226
---
12201227
# constructors
12211228

0 commit comments

Comments
 (0)