Skip to content

add 60-asynchronous-programming module #780

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test:
@ test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
name: esperar
theory: |
JavaScript es de un solo subproceso, lo que significa que solo puede realizar una tarea a la vez.

Para gestionar tareas que requieren tiempo (como la espera, la obtención de datos o los temporizadores) sin congelar el programa, JavaScript utiliza funciones asíncronas.

Una herramienta asíncrona básica es setTimeout. Esta herramienta programa una función (llamada callback) para que se ejecute tras un retraso especificado (en milisegundos).

setTimeout acepta dos argumentos:
1. Una función callback: una función que se ejecuta posteriormente, que se pasa como argumento a otra función.
2. Un tiempo de retraso en milisegundos.

Ejemplo:

```js
const cb = () => {
  console.log('Hello after 1 second');
};

setTimeout(cb, 1000);
// La devolución de llamada no se llama antes de este momento (pero no necesariamente exactamente en ese momento).
// A menudo ocurre más tarde debido al bucle de eventos y a las particularidades del lenguaje.
```

instructions: |
Implemente la función waitFor(ms, callback) que llama a la devolución de llamada pasada después de ms milisegundos usando setTimeout.

```js
waitFor(1000, () => {
console.log('1 second has passed');
});
```

tips:
- |
[setTimeout](https://developer.mozilla.org/es/docs/Web/API/setTimeout)
- |
[Callback](https://developer.mozilla.org/es/docs/Web/JavaScript/Guide/Callbacks)
definitions:
- name: Función de callback
description: Función pasada como argumento a otra función para ser llamada más adelante.
- name: Temporizador
description: Mecanismo para ejecutar una función después de cierto tiempo.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Implement the function waitFor(ms, callback) that calls the passed callback after ms milliseconds using setTimeout.

```js
waitFor(1000, () => {
console.log('1 second has passed');
});
```
20 changes: 20 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
JavaScript is single-threaded, which means it can do only one thing at a time.
To handle tasks that take some time (like waiting, fetching data, or timers) without freezing the program, JavaScript uses asynchronous functions.

One basic asynchronous tool is setTimeout. It schedules a function (called a callback) to run after a specified delay (in milliseconds).

- setTimeout accepts two arguments:
  1. A callback function — a function to run later, passed as an argument to another function.
  2. A delay time in milliseconds.

Example:

```js
const cb = () => {
  console.log('Hello after 1 second');
};

setTimeout(cb, 1000);
// The callback is called not before this time (but not necessarily exactly at the moment).
// Often it happens later due to the event loop and language specifics.
```
12 changes: 12 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
name: wait for
tips:
- |
[setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)
- |
[Callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Callbacks)
definitions:
- name: Callback
description: A function passed as an argument to another function for subsequent invocation
- name: Timer
description: A mechanism for executing a function after a certain amount of time has passed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Implemente la función waitFor(ms, callback) que llama a la devolución de llamada pasada después de ms milisegundos usando setTimeout.

```js
waitFor(1000, () => {
console.log('1 second has passed');
});
```
21 changes: 21 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/es/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
JavaScript es de un solo subproceso, lo que significa que solo puede realizar una tarea a la vez.

Para gestionar tareas que requieren tiempo (como la espera, la obtención de datos o los temporizadores) sin congelar el programa, JavaScript utiliza funciones asíncronas.

Una herramienta asíncrona básica es setTimeout. Esta herramienta programa una función (llamada callback) para que se ejecute tras un retraso especificado (en milisegundos).

setTimeout acepta dos argumentos:
1. Una función callback: una función que se ejecuta posteriormente, que se pasa como argumento a otra función.
2. Un tiempo de retraso en milisegundos.

Ejemplo:

```js
const cb = () => {
  console.log('Hello after 1 second');
};

setTimeout(cb, 1000);
// La devolución de llamada no se llama antes de este momento (pero no necesariamente exactamente en ese momento).
// A menudo ocurre más tarde debido al bucle de eventos y a las particularidades del lenguaje.
```
12 changes: 12 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/es/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
name: esperar
tips:
- |
[setTimeout](https://developer.mozilla.org/es/docs/Web/API/setTimeout)
- |
[Callback](https://developer.mozilla.org/es/docs/Web/JavaScript/Guide/Callbacks)
definitions:
- name: Función de callback
description: Función pasada como argumento a otra función para ser llamada más adelante.
- name: Temporizador
description: Mecanismo para ejecutar una función después de cierto tiempo.
7 changes: 7 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// BEGIN
const waitFor = (ms, cb) => {
setTimeout(cb, ms);
};
// END

export default waitFor;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Реализуйте функцию waitFor(ms, callback), которая вызывает переданный cb через ms миллисекунд, используя setTimeout.

```js
waitFor(1000, () => {
console.log('1 second has passed');
});
```
20 changes: 20 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/ru/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
JavaScript является однопоточным, что означает, что он может выполнять только одну задачу за раз.
Для обработки задач, требующих времени (например, ожидания, извлечения данных или таймеров) без замораживания программы, JavaScript использует асинхронные функции.

Одним из основных асинхронных инструментов является setTimeout. Он планирует выполнение функции (называемой обратным вызовом) после указанной задержки (в миллисекундах).

- setTimeout принимает два аргумента:
1. Функция обратного вызова — функция для выполнения позже, переданная в качестве аргумента другой функции.
2. Время задержки в миллисекундах.

Пример:

```js
const cb = () => {
  console.log('Hello after 1 second');
};

setTimeout(cb, 1000);
// Коллбек выполняется не ранее этого времени (но не обязательно именно в этот момент).
// Часто это происходит позже из-за цикла событий и специфики языка.
```
12 changes: 12 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/ru/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
name: ждать
tips:
- |
[setTimeout](https://developer.mozilla.org/ru/docs/Web/API/setTimeout)
- |
[коллбек](https://developer.mozilla.org/ru/docs/Web/JavaScript/Guide/Callbacks)
definitions:
- name: Коллбек
description: Функция, переданная в качестве аргумента другой функции для последующего вызова
- name: Таймер
description: Механизм выполнения функции по истечении определенного времени.
20 changes: 20 additions & 0 deletions modules/60-asynchronous-programming/010-setTimeout/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { expect, test, vi} from 'vitest';
import f from './index.js';

test('delay occurred', () => {
vi.useFakeTimers();

const callback = vi.fn();

f(100, callback);

expect(callback).not.toHaveBeenCalled();

vi.advanceTimersByTime(99);
expect(callback).not.toHaveBeenCalled();

vi.advanceTimersByTime(1);
expect(callback).toHaveBeenCalledTimes(1);

vi.useRealTimers();
});
2 changes: 2 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test:
@ test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
name: Espera la promesa
theory: |
JavaScript es de un solo subproceso. Para evitar que la ejecución del programa se congele mientras se espera (por ejemplo, una respuesta de un servidor o un temporizador), se utiliza la ejecución asíncrona. Una forma de hacerlo es mediante promesas.

Una promesa es un objeto que representa el resultado de una operación asíncrona y que puede recibirse ahora, más tarde o nunca. Una promesa tiene tres estados:

- pendiente: en espera;
- cumplido: completado correctamente;
- rechazado: se produjo un error.

El estado se controla mediante:
- resolver: se ejecuta al completarse correctamente;
- rechazar: se ejecuta al fallar.

```js
const promise = new Promise((resolve, reject) => {
if (success) { // condicionalmente, todo se completó correctamente
resolve('Result of the entire execution');
} else {
reject(new Error('Error during execution'));
}
});
```
instructions: |
Implementar una función waitPromise(ms, reject) que devuelva una promesa.

La promesa debe:

- resolverse con la cadena "¡Listo!" después de ms milisegundos si no se pasa la instrucción reject o esta es falsa.

- rechazar con el error "¡Error!" después de ms milisegundos si la instrucción reject es verdadera.

Usar setTimeout para retrasar la ejecución.

Ejemplo:

```js
waitPromise(1000).then(console.log); // después de 1 segundo, imprime "Done!"

waitPromise(1000, true).catch(console.log); // después de 1 segundo, imprime "Failed!"
```
tips:
- >
[setTimeout](https://developer.mozilla.org/es/docs/Web/API/setTimeout)
- >
[Promise](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise)
definitions:
- name: Promesa
description: Un objeto que representa el resultado de una operación asincrónica, ya sea exitosa o errada.
17 changes: 17 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Implement a waitPromise(ms, reject) function that returns a promise.

The promise should:

- resolve with the string "Done!" after ms milliseconds if reject is not passed or is false.

- reject with the error "Failed!" after ms milliseconds if reject is true.

Use setTimeout to delay.

Example:

```js
waitPromise(1000).then(console.log); // after 1 second prints "Done!"

waitPromise(1000, true).catch(console.log); // after 1 second prints "Failed!"
```
21 changes: 21 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
JavaScript is single-threaded. To avoid freezing program execution while waiting (for example, for a response from a server or a timer), asynchronous execution is used. One way is to use promises.

A promise is an object representing the result of an asynchronous operation that can be received now, later, or never. A promise has 3 states:

- pending - waiting;
- fulfilled - successfully completed;
- rejected - an error occurred.

The state is controlled by:
- resolve is executed upon successful completion
- reject is executed upon failure

```js
const promise = new Promise((resolve, reject) => {
if (success) { // conditionally everything was completed successfully
resolve('Result of the entire execution');
} else {
reject(new Error('Error during execution'));
}
});
```
10 changes: 10 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
name: Wait Promise
tips:
- >
[setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)
- >
[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
definitions:
- name: Promise
description: An object representing the result of an asynchronous operation, either success or error.
17 changes: 17 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/es/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Implementar una función waitPromise(ms, reject) que devuelva una promesa.

La promesa debe:

- resolverse con la cadena "¡Listo!" después de ms milisegundos si no se pasa la instrucción reject o esta es falsa.

- rechazar con el error "¡Error!" después de ms milisegundos si la instrucción reject es verdadera.

Usar setTimeout para retrasar la ejecución.

Ejemplo:

```js
waitPromise(1000).then(console.log); // después de 1 segundo, imprime "Done!"

waitPromise(1000, true).catch(console.log); // después de 1 segundo, imprime "Failed!"
```
21 changes: 21 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/es/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
JavaScript es de un solo subproceso. Para evitar que la ejecución del programa se congele mientras se espera (por ejemplo, una respuesta de un servidor o un temporizador), se utiliza la ejecución asíncrona. Una forma de hacerlo es mediante promesas.

Una promesa es un objeto que representa el resultado de una operación asíncrona y que puede recibirse ahora, más tarde o nunca. Una promesa tiene tres estados:

- pendiente: en espera;
- cumplido: completado correctamente;
- rechazado: se produjo un error.

El estado se controla mediante:
- resolver: se ejecuta al completarse correctamente;
- rechazar: se ejecuta al fallar.

```js
const promise = new Promise((resolve, reject) => {
if (success) { // condicionalmente, todo se completó correctamente
resolve('Result of the entire execution');
} else {
reject(new Error('Error during execution'));
}
});
```
10 changes: 10 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/es/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
name: Espera la promesa
tips:
- >
[setTimeout](https://developer.mozilla.org/es/docs/Web/API/setTimeout)
- >
[Promise](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise)
definitions:
- name: Promesa
description: Un objeto que representa el resultado de una operación asincrónica, ya sea exitosa o errada.
15 changes: 15 additions & 0 deletions modules/60-asynchronous-programming/020-newPromise/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// BEGIN
const waitPromise = (ms, shouldFail = false) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject('Failed!');
} else {
resolve('Done!');
}
}, ms);
});
}
// END

export default waitPromise;
Loading