V
V
Vyacheslav2019-04-29 00:55:36
Node.js
Vyacheslav, 2019-04-29 00:55:36

What is the correct way to return a Promise in Javascript?

Hello, how to correctly beat this situation:
I am writing an asynchronous function for checking (validating) the incoming JSON and I don’t understand how to correctly return a promise, i.e. several options:
1. something like

return new Promise((resolve, reject) => {
...
if(valid) { resolve(...) } else { reject(errors) }
})

and then catch via await try catch or .then() .catch()
or do without reject
2.
return new Promise((resolve) => {
...
if(valid) { resolve() } else { resolve(errors) }
})

and catch it
const error = await ValidationFunc()
if(error){...} else {...}

Those. both options work equally well, but still I'm trying to understand how it would be semantically correct and in what situations to use one or another option

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Terentiev, 2019-04-29
@lmnsky84

In my opinion, the first option should be used.
The whole essence of Promise is that from the initial state we can go to the state
* completed (fulfilled): the operation was completed successfully.
* rejected (rejected): The operation ended with an error.
logically, if an error occurred during an asynchronous operation, then we must do reject (errors) and further handle the exception in catch ().
The second option may not work correctly in the Promise.all(iterable) chain when you need the explicitly executed result of several Promises.

A
Andrey Skorzhinsky, 2017-03-29
@NnovichokAdmin

First, look at the logs - the win and sql server event log, and then we will put forward hypotheses and refute them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question