-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07.js
More file actions
62 lines (50 loc) · 1.5 KB
/
07.js
File metadata and controls
62 lines (50 loc) · 1.5 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
60
61
62
const miPromesa = new Promise((resolve, reject) => {
setTimeout(() => {
const exito = true;
if (exito) {
resolve("La operación fue exitosa");
} else {
reject("La operación falló");
}
}, 2000);
})
// console.log(miPromesa);
// Los estados de las promesas son inmutables
const promesaResuelta = new Promise((resolve, reject) => {
resolve("primer valor");
resolve("segundo valor"); // Ignorado — ya estaba fulfilled
reject(new Error("error")); // Ignorado — ya estaba fulfilled
});
//promesaResuelta.then(valor => console.log(valor)); // "primer valor"
// Consumir valores de una promesa con .then() y a
function obtenerNombre(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (data) {
reject(new Error("Algo salió mal"));
} else {
resolve("María");
}
}, 500);
});
}
// Cambia true por false para ver el otro comportamiento
obtenerNombre(false)
.then(nombre => {
console.log("Hola,", nombre);
})
.catch(error => {
console.error("Error:", error.message);
});
// Aplicación real, llamando API Colombia
fetch("https://api-colombia.com/api/v1/Department")
.then((res) => res.json())
.then((departments) => {
console.log("Primer departamento:", departments[35].name);
departments.forEach((dep) => {
console.log(`${dep.name}: ${dep.population}`);
});
})
.catch((error) => {
console.error("Error consultando API Colombia:", error);
});