Answer the question
In order to leave comments, you need to log in
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) }
})
return new Promise((resolve) => {
...
if(valid) { resolve() } else { resolve(errors) }
})
const error = await ValidationFunc()
if(error){...} else {...}
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question