So I have a function that should immediatly return a rejected or resolved Promise, i.e. it is basically a snychronous function I want to "promisify".
What I usually do in such cases is something like this:
func() {
// some code to check for an error
if (hasError)
return Promise.reject(new Error("Failure"));
}
return Promise.resolve("Success");
}
Now, with the availability of "async" functions in ES2017 it seems like I could also do this:
async func() {
// some code to check for an error
if (hasError)
throw new Error("Failure");
}
return "Success";
}
So I basically use async
just to "promisify" my function, without using await
in the function body anywhere. As I see it, this variant should be doing exactly the same. Am I right, or are there any additional side effects I am not aware of here?
I think I would prefer this pattern, as it is a bit shorter, it is very clear from the function definition alone that it is async, and any JavaScript errors (like type errors) would also lead to a rejection which makes my overall code react more gracefully in case of unexpected errors.