-
Notifications
You must be signed in to change notification settings - Fork 704
Добавляет "На практике" в Promise.try() #5988
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
zheleznikov
wants to merge
8
commits into
doka-guide:main
Choose a base branch
from
zheleznikov:js-promise-try-advice
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f3ad162
promise-try advice added
zheleznikov 8cef7eb
promise-try advice added
zheleznikov 2cae3fe
promise-try advice added
zheleznikov 1085f59
Promise.try() practice text improved
zheleznikov 647d438
linter issues fixed
zheleznikov 82da445
Promise.try() text conclusion improved
zheleznikov 57c3f06
Promise.try() text conclusion improved
zheleznikov 5ee0c7d
linter issues fixed
zheleznikov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| 🛠 `Promise.try()` может пригодиться в UI-китах и библиотеках, которые принимают колбэк и не знают заранее, вернёт ли он значение, промис или выбросит ошибку. | ||
|
|
||
| Предположим, что компонент формы принимает обработчик `onSubmit`. Пользователь библиотеки может передать в него функцию, которая: | ||
|
|
||
| - возвращает синхронный результат; | ||
| - возвращает промис; | ||
| - выбрасывает ошибку ещё до начала асинхронной операции. | ||
|
|
||
| Задача компонента - одинаково обработать успешный результат и ошибку в любом из этих случаев. Для этого можно обернуть вызов `onSubmit` в `Promise.try()`: | ||
|
|
||
| ```js | ||
| function handleSubmit(onSubmit) { | ||
| Promise.try(onSubmit) | ||
| .then((result) => { | ||
| console.log('Успех:', result) | ||
| }) | ||
| .catch((error) => { | ||
| console.error('Ошибка:', error.message) | ||
| }) | ||
| } | ||
| ``` | ||
|
|
||
| Теперь `handleSubmit()` сможет единообразно обработать любой вариант `onSubmit`: | ||
|
|
||
| ```js | ||
| // Синхронный обработчик | ||
| handleSubmit(() => { | ||
| return 'Форма отправлена' | ||
| }) | ||
| // Успех: Форма отправлена | ||
|
|
||
| // Асинхронный обработчик | ||
| handleSubmit(() => { | ||
| return Promise.resolve('Данные отправлены на сервер') | ||
| }) | ||
| // Успех: Данные отправлены на сервер | ||
|
|
||
| // Обработчик с ошибкой | ||
| handleSubmit(() => { | ||
| throw new Error('Поле email обязательно') | ||
| }) | ||
| // Ошибка: Поле email обязательно | ||
| ``` | ||
|
|
||
| Во всех случаях результат попадёт в `then()`, а ошибка — в `catch()`. | ||
|
|
||
| `Promise.try()` возвращает промис, поэтому результат `onSubmit` можно обрабатывать одинаково, независимо от того, синхронная это функция или асинхронная. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. По-моему эта мысль уже сказана в предыдущем предложении |
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Давай прокинем в аргументы formData? Реальный обработчик формы почти всегда принимает данные формы. Было бы полезно показать вариант с передачей данных. Это и полнее раскрывает API, и ближе к реальному использованию
Ну и
returnя бы дописал