-
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 russian languages. Add russian translation for help and for wat…
…erfall exercises.
- Loading branch information
Andrew Mikhailov
committed
May 21, 2016
1 parent
d5d2de0
commit 8041f5e
Showing
5 changed files
with
101 additions
and
1 deletion.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,3 +13,4 @@ results | |
|
||
npm-debug.log | ||
node_modules | ||
.idea/ |
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,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,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,13 @@ | ||
{ | ||
"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" | ||
} | ||
} |