@@ -1059,39 +1059,6 @@ console.log(add(5, 2)); // 7
1059
1059
When you declare functions in expressions you don't need to
1060
1060
give them a name.
1061
1061
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
- ` ` `
1095
1062
---
1096
1063
# higher-order functions
1097
1064
@@ -1216,6 +1183,46 @@ console.log(n.add(5)); // 105
1216
1183
console .log (n .multiply (3 )); // 315
1217
1184
` ` `
1218
1185
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
+
1219
1226
---
1220
1227
# constructors
1221
1228
0 commit comments