Created
August 4, 2023 15:36
-
-
Save zeluizr/df0034693669cb22d2e6311270ac998e to your computer and use it in GitHub Desktop.
Cola de Procesos con Promesas, Queue y Programación Funcional, PROGRAMACIÓN AVANZADA EN JAVASCRIPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Queue { | |
#items = []; | |
enqueue(item) { | |
this.#items.push(item); | |
} | |
dequeue() { | |
return this.#items.shift(); | |
} | |
isEmpty() { | |
return this.#items.length === 0; | |
} | |
} | |
const promise = new Promise((res, rej) => { | |
setTimeout(() => { | |
res("promesa 1"); | |
}, 4000); | |
}); | |
// promise.then((res) => console.log(res)); | |
// (async () => { | |
// const data = await promise; | |
// console.log(data); | |
// })(); | |
function promiseWait(time, message) { | |
return () => { | |
return new Promise((res, rej) => { | |
setTimeout(() => { | |
res(message); | |
}, time); | |
}); | |
}; | |
} | |
function fetchWaiting(time, url) { | |
return async () => { | |
await new Promise((r) => setTimeout(r, time)); | |
return fetch(url).then((res) => res.json()); | |
}; | |
} | |
const queue = new Queue(); | |
// queue.enqueue( | |
// new Promise((res, rej) => { | |
// setTimeout(() => { | |
// res("promesa 1"); | |
// }, 4000); | |
// }) | |
// ); | |
// queue.enqueue( | |
// new Promise((res, rej) => { | |
// setTimeout(() => { | |
// res("promesa 2"); | |
// }, 4000); | |
// }) | |
// ); | |
queue.enqueue([promiseWait(4000, "promesa 1"), (data) => console.log(data)]); | |
queue.enqueue([promiseWait(4000, "promesa 2"), (data) => console.log(data)]); | |
queue.enqueue([ | |
fetchWaiting(2000, "https://jsonplaceholder.typicode.com/todos/1"), | |
(data) => console.log(data), | |
]); | |
queue.enqueue([ | |
fetchWaiting(1000, "https://jsonplaceholder.typicode.com/todos/2"), | |
(data) => console.log(data), | |
]); | |
run(); | |
async function run() { | |
while (!queue.isEmpty()) { | |
const [res, fn] = await queue.dequeue(); | |
const data = await res(); | |
fn(data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment