Markdown corrections, Russian translation and more (#24803)
1. Fixed markdown for proper render of code examples. 2. Added missing translation. 3. Translated comments. 4. Turned bits of code back english ( like function() instead of функция() ). 5. Fixed page styling structure.pull/21122/head^2
parent
d7bb602130
commit
23c5c1baf4
|
@ -8,85 +8,113 @@ localeTitle: Ожидание обещаний
|
||||||
|
|
||||||
Чтобы понять эту тему, вы должны иметь четкое представление о том, как работают [Обещания](https://guide.freecodecamp.org/javascript/promises) .
|
Чтобы понять эту тему, вы должны иметь четкое представление о том, как работают [Обещания](https://guide.freecodecamp.org/javascript/promises) .
|
||||||
|
|
||||||
* * *
|
---
|
||||||
|
|
||||||
## Основной синтаксис
|
## Основной синтаксис
|
||||||
|
|
||||||
\`\` \`javascript функция медленноResolvedPromiseFunc (строка) { return new Promise (solve => { setTimeout (() => { разрешения (строка); }, 5000); }); }
|
``` javascript
|
||||||
|
function slowlyResolvedPromiseFunc(string) {
|
||||||
асинхронная функция doIt () { const myPromise = ждать медленноResolvedPromiseFunc ("foo"); console.log (myPromise); // "foo" }
|
return new Promise(resolve => {
|
||||||
|
setTimeout(() => {
|
||||||
сделай это();
|
resolve(string);
|
||||||
```
|
}, 5000);
|
||||||
There are a few things to note:
|
});
|
||||||
|
|
||||||
* The function that encompasses the `await` declaration must include the `async` operator. This will tell the JS interpreter that it must wait until the Promise is resolved or rejected.
|
|
||||||
* The `await` operator must be inline, during the const declaration.
|
|
||||||
* This works for `reject` as well as `resolve`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Nested Promises vs. `Async` / `Await`
|
|
||||||
|
|
||||||
Implementing a single Promise is pretty straightforward. In contrast, Chained Promises or the creation of a dependency pattern may produce "spaghetti code".
|
|
||||||
|
|
||||||
The following examples assume that the <a href='https://github.com/request/request-promise' target='_blank' rel='nofollow'>`request-promise`</a> library is available as `rp`.
|
|
||||||
|
|
||||||
### Chained/Nested Promises
|
|
||||||
```
|
|
||||||
|
|
||||||
Javascript // Первое обещание const fooPromise = rp ("http://domain.com/foo");
|
|
||||||
|
|
||||||
fooPromise.then (resultFoo => { // Должен дождаться "foo", чтобы разрешить console.log (resultFoo);
|
|
||||||
```
|
|
||||||
const barPromise = rp("http://domain.com/bar");
|
|
||||||
const bazPromise = rp("http://domain.com/baz");
|
|
||||||
|
|
||||||
return Promise.all([barPromise, bazPromise]);
|
|
||||||
```
|
|
||||||
|
|
||||||
}), затем (resultArr => { // Обрабатываем разрешения «bar» и «baz» здесь console.log (resultArr \[0\]); console.log (resultArr \[1\]); });
|
|
||||||
```
|
|
||||||
### `async` and `await` Promises
|
|
||||||
```
|
|
||||||
|
|
||||||
Javascript // Оберните все в асинхронной функции асинхронная функция doItAll () { // Получить данные из конечной точки «foo», но дождаться разрешения console.log (ожидание rp ("http://domain.com/foo"));
|
|
||||||
```
|
|
||||||
// Concurrently kick off the next two async calls,
|
|
||||||
// don't wait for "bar" to kick off "baz"
|
|
||||||
const barPromise = rp("http://domain.com/bar");
|
|
||||||
const bazPromise = rp("http://domain.com/baz");
|
|
||||||
|
|
||||||
// After both are concurrently kicked off, wait for both
|
|
||||||
const barResponse = await barPromise;
|
|
||||||
const bazResponse = await bazPromise;
|
|
||||||
|
|
||||||
console.log(barResponse);
|
|
||||||
console.log(bazResponse);
|
|
||||||
```
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Наконец, вызовите функцию async doItAll (). then (() => console.log ('Done!'));
|
async function doIt() {
|
||||||
|
const myPromise = await slowlyResolvedPromiseFunc("foo");
|
||||||
|
console.log(myPromise); // "foo"
|
||||||
|
}
|
||||||
|
|
||||||
|
doIt();
|
||||||
|
|
||||||
```
|
```
|
||||||
The advantages of using `async` and `await` should be clear. This code is more readable, modular, and testable.
|
Следует отметить несколько моментов:
|
||||||
|
|
||||||
It's fair to note that even though there is an added sense of concurrency, the underlying computational process is the same as the previous example.
|
* Функция, которая заключаетв себе объявление `await` должна содержать оператор `async`. Это подскажит Инттерпретатору JS, что нужно дождаться разрешение и отвержения resolve.
|
||||||
|
* Оператор `await` должен быть подключен во время объявления const.
|
||||||
|
* Это работает как для `reject`, так и для `resolve`
|
||||||
|
There are a few things to note:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Handling Errors / Rejection
|
## Вложенные Promises vs. `Async` / `Await`
|
||||||
|
|
||||||
|
Реализация одного Promise довольно просто. В отличии от Цепочки Promises или создания набора зависимостей, что может привести с созданию "spagetti code" ("спагетти из кода").
|
||||||
|
|
||||||
|
В следующих примерах подразумевается, что библитека <a href='https://github.com/request/request-promise' target='_blank' rel='nofollow'>`request-promise`</a> доступна по `rp`.
|
||||||
|
|
||||||
A basic try-catch block handles a rejected Promise.
|
### Цепочки / Вложенные Promises
|
||||||
|
|
||||||
|
``` javascript
|
||||||
|
// Первый Promise
|
||||||
|
const fooPromise = rp("http://domain.com/foo");
|
||||||
|
|
||||||
|
fooPromise.then(resultFoo => {
|
||||||
|
// Ожидайте разрешения "foo"
|
||||||
|
console.log(resultFoo);
|
||||||
|
|
||||||
|
const barPromise = rp("http://domain.com/bar");
|
||||||
|
const bazPromise = rp("http://domain.com/baz");
|
||||||
|
|
||||||
|
return Promise.all([barPromise, bazPromise]);
|
||||||
|
}).then(resultArr => {
|
||||||
|
// Обрабатываем разрешения «bar» и «baz» здесь
|
||||||
|
console.log(resultArr[0]);
|
||||||
|
console.log(resultArr[1]);
|
||||||
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Javascript async function errorExample () { пытаться { const rejectPromise = ждать Promise.reject («О-о!»); } catch (ошибка) { console.log (ошибка); // «О-о!» } }
|
### `async` и `await` Promises
|
||||||
|
|
||||||
errorExample (); \`\` \`
|
``` javascript
|
||||||
|
// Оберните все в асинхронную функцию
|
||||||
|
async function doItAll() {
|
||||||
|
// Получите данные из конечной точки "foo", но дождаться разрешения
|
||||||
|
console.log(await rp("http://domain.com/foo"));
|
||||||
|
|
||||||
* * *
|
// Параллельно запустите следующие две асинхронные функции,
|
||||||
|
// не ждите пока "bar" запустит "baz"
|
||||||
|
const barPromise = rp("http://domain.com/bar");
|
||||||
|
const bazPromise = rp("http://domain.com/baz");
|
||||||
|
|
||||||
|
// Когда обе запуститлись параллельно, ждите обе
|
||||||
|
const barResponse = await barPromise;
|
||||||
|
const bazResponse = await bazPromise;
|
||||||
|
|
||||||
|
console.log(barResponse);
|
||||||
|
console.log(bazResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Наконец, вызовите асинхронную функцию
|
||||||
|
doItAll().then(() => console.log('Done!'));
|
||||||
|
```
|
||||||
|
|
||||||
|
Преимущества использования `async` и `await` должны быть ясны. Этот код более читабельный, модульный и поддающийся тестированию.
|
||||||
|
|
||||||
|
Справедливо заметить, что не смотря на большую степень параллелилизма, лежащий в основе вычислительный процесс идентичен тому из предыдущего примераю
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Разрешение Ошибок / Rejection
|
||||||
|
|
||||||
|
Обыкновенный блок попытка-перехват разрешит отвергнутый Promise.
|
||||||
|
|
||||||
|
``` javascript
|
||||||
|
async function errorExample() {
|
||||||
|
try {
|
||||||
|
const rejectedPromise = await Promise.reject("Oh-oh!");
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error); // "Uh-oh!"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
errorExample();
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
#### Дополнительная информация:
|
#### Дополнительная информация:
|
||||||
|
|
||||||
* `await` Операторы [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
|
* `await` Операторы [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
|
||||||
* `async` Оператор функций [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function)
|
* `async` Оператор функций [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function)
|
||||||
|
|
Loading…
Reference in New Issue