-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcall_back.js
More file actions
62 lines (41 loc) · 1.86 KB
/
call_back.js
File metadata and controls
62 lines (41 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Example callbacks js async
//##############################################################################################
//CALLBACK HELL issue complex nested callbacks
// Not error but difficult to read and fix code if 1 function nested error -> all function error
// function printString(string, callback){
// setTimeout(()=>{
// console.log(string)
// callback()
// },1000)
// }
// function printAll(){
// printString("String A!",()=>{
// printString("String B!",()=>{
// printString("String C!",()=>{
// })
// })
// })
// }
// printAll()
//#########################################################################################
//Callbacks to handle ansync
// -----------------------------
// Usually: access values fro database, downloading images, reading files
// When 1 process is running after finished we can call another function to run and finished
// then process initate will run continue
// 1 type of high order function
//---------------------------------
const fs = require('fs');
const request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback) // in line 46 when download complete will run function call back
// if not then terminate download function and no run call back
});
};
// in this line you can see i run function download with callback = function =()=>{console.log('done')}
// Meaning when i run download then function download run but not finished this run line 46
download('https://www.google.com/images/srpr/logo3w.png', './images/google.png', function(){
console.log('done');
});
//=> this example overviews when using callback function then ansync because download function non finished then callback function run