You can use the Promise.reject()
method to create a promise that is rejected with the given reason.
What is the advantage of returning a rejected promise rather than just throwing an error (as in previous example). The stack trace is available in both cases, just not sure I fully understand the purpose of Promise.reject
@Victor: Within an async
function, you can decide to go with either approach; both throwing an error and returning a rejected promise will result in a rejected promise being returned from the method.
However, there's a difference in behavior in a non-asynchronous function (one that's not declared using the async
keyword). If you throw an error, such a function will not return a rejected promise — it will let the error bubble up the call stack until the nearest catch
block (if any). Returning a rejected promise, on the other hand, will not cause an error to be thrown.