-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Ukrainian language and fix typo in Russian language
- Loading branch information
Showing
13 changed files
with
5,742 additions
and
3 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
Час від часу ви б хотіли викликати одну і ту ж саму функцію декілька разів, але | ||
з різними параметрами, **не турбуючись по те, які дані повертаються**, але | ||
перевіряючи, чи призводять виклики до помилок. | ||
|
||
В даному випадку буде корисним `async.each`. | ||
|
||
Наприклад, наступний код здійснює три виклики та використовує значення із масиву: | ||
|
||
```js | ||
var http = require('http') | ||
, async = require('async'); | ||
async.each(['cat', 'meerkat', 'penguin'], function(item, done){ | ||
var opts = { | ||
hostname: 'http://httpbin.org', | ||
path: '/post', | ||
method: 'POST' | ||
}; | ||
var req = http.request(opts, function(res){ | ||
res.on('data', function(chunk){ | ||
}); | ||
res.on('end', function(){ | ||
return done(); | ||
}); | ||
}); | ||
req.write(item); | ||
req.end(); | ||
}, | ||
function(err){ | ||
if (err) console.log(err); | ||
}); | ||
``` | ||
|
||
## Завдання | ||
|
||
Написати програму, яка отримує два URL, як перший та другий аргументи командної строки. | ||
|
||
Потім, використовуючи `http.get`, зробити два GET запити, по одному на кожен URL, | ||
і `console.log` на будь-які помилки. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
З `async.each` результати асинхронної функції будуть **втрачені**. | ||
|
||
На допомогу приходить `async.map`. Він робить те ж саме, що і `async.each`, | ||
шляхом виклику асинхронної функції ітератора на масив, але **збирає результат** | ||
асинхронної функції ітератора і передає його в функцію зворотнього виклику. | ||
|
||
Результати будуть представлені у вигляді масиву, який знаходитиметься **в тому ж порядку**, | ||
що і у вхідному масиві. | ||
|
||
Приклад в EACH-завданні можна записати в такому вигляді: | ||
|
||
```js | ||
var http = require('http') | ||
, async = require('async'); | ||
async.map(['cat', 'meerkat', 'penguin'], function(item, done){ | ||
var opts = { | ||
hostname: 'http://httpbin.org', | ||
path: '/post', | ||
method: 'POST' | ||
}; | ||
var body = ''; | ||
var req = http.request(opts, function(res){ | ||
res.on('data', function(chunk){ | ||
body += chunk.toString(); | ||
}); | ||
res.on('end', function(){ | ||
return done(null, body); | ||
}); | ||
}); | ||
req.write(item); | ||
req.end(); | ||
}, | ||
function(err, results){ | ||
if (err) return console.log(err); | ||
// Результати - це масив тіл відповідей в тому ж порядку. | ||
}); | ||
``` | ||
|
||
## Завдання | ||
|
||
Напишіть програму, яка прийматиме два аргументи командної строки для двох URL. | ||
|
||
Використайте `http.get`, щоб здійснити два GET-запити по цим URL. | ||
|
||
Вам буде потрібно використати `async.map`, а потім `console.log` для результуючого масиву. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
## Завдання | ||
Напишіть програму, яка буде отримувати URL в якості першого аргументу командної строки. | ||
|
||
Кожне із значень в массиві заданому нижче, використайте для відправки GET-запиту на URL, | ||
за допомогою `http.get` як параметр запиту `number`: | ||
|
||
```js | ||
['one', 'two', 'three'] | ||
``` | ||
Кожного разу конвертуйте тіло відповіді в `Number` і додавайте його до попереднього значення. | ||
`console.log` для виводу фінального результату. | ||
|
||
## Поради | ||
|
||
Використовуйте `async.reduce`: | ||
|
||
https://github.com/caolan/async#reduce |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
В цьому завданні ми навчимося використовувати `async.series`. | ||
|
||
Основна відмінність між функціями `waterfall` і `series` в тому, що результат функції | ||
в `async.series` **не буде передаватися** до наступної функції після її виконання. | ||
`series` буде **збирати всі результати у вигляді масиву** і передавати їх | ||
**в опціональну функцію зворотнього виклику**, яка відпрацює **за один раз, | ||
як тільки всі функції виконаються**. | ||
Наприклад: | ||
|
||
```js | ||
async.series([ | ||
function(callback){ | ||
setTimeout(function() { | ||
callback(null, 'one'); | ||
}, 200); | ||
}, | ||
function(callback){ | ||
setTimeout(function() { | ||
callback(null, 'two'); | ||
}, 100); | ||
} | ||
], | ||
// Опціональна функція зворотнього виклику. | ||
function(err, results){ | ||
// Результат тепер буде рівний ['one', 'two'] | ||
}); | ||
``` | ||
Замість використання масиву, як вмістилища для результату `async.series` можна | ||
використовувати об'єкт, запускаючи кожну властивість і створюючи об'єкт в якості | ||
результату з тими ж властивостями. Приклад вище можна переписати таким чином: | ||
|
||
```js | ||
async.series({ | ||
one: function(done){ | ||
done(null, '1'); | ||
}, | ||
two: function(done){ | ||
done(null, '2'); | ||
} | ||
}, function(err, results){ | ||
console.log(results); | ||
// Результатом буде {one: 1, two: 2} | ||
}); | ||
``` | ||
|
||
## Завдання | ||
|
||
Напишіть програму, яка приймає два URL, в якості першого і другого аргументів | ||
командної строки. | ||
|
||
Використовуючи `http.get`, створіть GET запит на ці URL і передайте тіло відповіді в | ||
функцію зворотнього виклику. | ||
|
||
Передайте в функцію `async.series` об'єкт, використовуючи властивості `requestOne` і | ||
`requestTwo`. | ||
|
||
Використайте `console.log` для виводу результатів, коли всі функції виконаються. |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# Завдання | ||
|
||
Напишіть програму, яка приймає два аргументи командної строки, які | ||
містять хост і порт. Використайте `http.request` та відправте POST-запит на | ||
|
||
```js | ||
url + '/users/create' | ||
``` | ||
з тілом, яке містить `JSON.stringify` об'єкт: | ||
|
||
```js | ||
{"user_id": 1} | ||
``` | ||
|
||
Зробіть це п'ять разів, щоразу збільшуючи властивість `user_id`, починаючи з 1. | ||
|
||
Коли запити будуть завершені, відправте GET-запит на: | ||
|
||
```js | ||
url + '/users' | ||
``` | ||
|
||
використайте `console.log` на тіло відповіді від GET-запиту. | ||
|
||
## Поради | ||
|
||
В цьому завданні, вам буде необхідно координувати декілька асинхронних операцій. | ||
|
||
Використайте `async.series` для цього і передайте в `Object`. В одній з функцій | ||
потрібно використати `async.times`, щоб відправити POST-request використовуючи `http.request`. | ||
Інша буде робити GET-запит. | ||
|
||
Ви можете прочитать більше про `async.times` тут: | ||
|
||
https://github.com/caolan/async#times |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
В Node.js та бра́узерах є 3 способи реалізувати **асинхронний** JavaScript. | ||
|
||
Перший призводить до того, що ми називаємо **Callback Hell**. | ||
Callback Hell можна звести до мінімуму, якщо слідувати порадам: | ||
http://callbackhell.com. | ||
|
||
Другой заключаєтся в використанні пакету `Promise`. Використовуючи `Promise` | ||
можна спростити код, але він також добавляє ще один рівень абстракції. | ||
|
||
Останній метод заключаєтся у використанні пакету `async`, створеного Caolan McMahon. | ||
Завдяки **async** ми все ще пишемо функції зворотнього виклику, але без використання | ||
Callback Hell чи додавання додаткового рівня абстракції від Promise. | ||
|
||
Найчастіше у вас буде необхідність робити декілька асинхронних викликів один за одним і | ||
кожен виклик буде в залежності від результату попереднього асинхронного виклику. | ||
Ми можемо зробити це за допомогою `async.waterfall`. | ||
|
||
Для прикладу розглянемо наступний код: | ||
|
||
1) Робимо запит GET на `http://localhost:3131` в функції waterfall. | ||
2) Тіло-відповідь передаєтся в якості аргументу до наступної функції waterfall через | ||
зворотній виклик. Друга функція в waterfall приймає тіло як | ||
параметр і використовує `JSON.parse`, щоб отримати властивість `port` | ||
та зробити інший GET запит. | ||
|
||
```js | ||
var http = require('http') | ||
, async = require('async'); | ||
|
||
async.waterfall([ | ||
function(cb){ | ||
var body = ''; | ||
// відповідь - це закодований JSON-об'єкт, як наступний приклад {порт: 3132} | ||
http.get("http://localhost:3131", function(res){ | ||
res.on('data', function(chunk){ | ||
body += chunk.toString(); | ||
}); | ||
res.on('end', function(){ | ||
cb(null, body); | ||
}); | ||
}).on('error', function(err) { | ||
cb(err); | ||
}); | ||
}, | ||
|
||
function(body, cb){ | ||
var port = JSON.parse(body).port; | ||
var body = ''; | ||
http.get("http://localhost:" + port, function(res){ | ||
res.on('data', function(chunk){ | ||
body += chunk.toString(); | ||
}); | ||
res.on('end', function(){ | ||
cb(null, body); | ||
}); | ||
}).on('error', function(err) { | ||
cb(err); | ||
}); | ||
} | ||
], function(err, result){ | ||
if (err) return console.error(err); | ||
console.log(result); | ||
}); | ||
``` | ||
|
||
## Завдання | ||
|
||
В цьому завданні вам потрібно написати програму, яка буде зчитувати вміст файлу. | ||
|
||
Шлях до файлу буде переданий, як перший аргумент командної строки | ||
(тобто `process.argv[2]`). | ||
|
||
Файл буде містити один URL. Використайте `http.get`, щоб зробити GET запит на | ||
цей URL і `console.log`, щоб вивести тіло відповіді. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
## Завдання | ||
|
||
Напишіть програму, яка буде приймати один аргумент командної строки як URL-адресу. | ||
|
||
Використовуючи `async.whilst` і `http.get`, відправте GET-запит на цей URL поки не отримаєте | ||
тіло відповіді, що містить рядок `"meerkat"`. | ||
|
||
`сonsole.log` кількості GET-запитів, необхідних для отримання "meerkat" рядка. | ||
|
||
## Поради | ||
|
||
`String.prototype.trim()` - це ваш приятель. | ||
Дізнайтесь більше про `async.whilst()` тут: | ||
|
||
https://github.com/caolan/async#whilst |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
{yellow}{bold}Існують проблеми з додатком {appname}?{/bold}{/yellow} | ||
|
||
Якщо ти шукаєш допомогу з Node.js, канал #Node.js | ||
на Freenode IRC - це чудове місце для пошуку охочих допомогти. | ||
Також тут є Node.js Google Group: | ||
https://groups.google.com/forum/#!forum/nodejs | ||
|
||
{yellow}{bold}Знайшов баг в додатку {appname} чи просто хочеш допомогти в розвитку проекту?{/bold}{/yellow} | ||
|
||
Офіційний репозиторій для додатку {appname}: | ||
https://github.com/bulkan/async-you/ | ||
Не соромтесь відправити звіт про помилку або (бажано) пул-реквест. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"title": "async you - навчіться використовувати пакет async", | ||
"subtitle": "\u001b[23mВиберіть вправу і натисніть клавішу \u001b[3mEnter\u001b[23m для початку", | ||
"exercise": { | ||
"WATERFALL": "waterfall", | ||
"SERIES OBJECT": "series object", | ||
"EACH": "each", | ||
"MAP": "map", | ||
"TIMES": "times", | ||
"REDUCE": "reduce", | ||
"WHILST": "whilst" | ||
} | ||
} | ||
|
Oops, something went wrong.