-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path04_promise.js
60 lines (53 loc) · 1.56 KB
/
04_promise.js
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
60
"use strict";
var fs = require('fs');
// función que lee un fichero retorna callBack
function leeFicheroCB( nomfile, callBack) {
fs.readFile(nomfile, 'utf8', function (err, data) {
console.log('versión callback');
if (err) {
return callBack(err);
}
return callBack(null, data);
});
}
// función que lee un fichero retorna promesa
function leeFicheroPROM( nomfile) {
console.log('versión promesa');
return new Promise(function(resolve, reject){
fs.readFile(nomfile, 'utf8', function (err, data) {
if (err) {
return reject(err);
}
return resolve(data);
});
});
}
// función que lee un fichero retorna promesa y callback
function leeFichero( nomfile, callBack) {
console.log('híbrida con ' + (callBack ? 'callBack' : 'promesa'));
return new Promise(function(resolve, reject){
fs.readFile(nomfile, 'utf8', function (err, data) {
if (err) {
if (callBack) {
return callBack(err);
}
return reject(err);
}
if (callBack) {
return callBack(null, data);
}
return resolve(data);
});
});
}
var file = './_ficherotexto.txt';
//leeFichero(file, function(err, data) {
// if (err) { return console.log('ERROR', err); }
// console.log(data);
//});
// leeFichero con promesa
leeFichero(file).then( function(data) {
console.log(data);
}).catch( function(err) {
console.log('ERROR', err);
});