The code written (without return ) is most likely fine until the caller needs access to the asynchronously received value.
First of all, async is required as part of the definition of your function ONLY if you plan to use await inside the function. If you are not using await inside (which your code does not show), then part of the async definition is not required. Thus, perhaps it will be just like this:
getUsers(res) { User.findAll().then(users => res.json(users)); }
Secondly, if the caller wants to use await in the getUsers() function, then he needs to return a promise (as you suggested). If the caller does not use await with him or else some access to the return value is needed, then return not required. So, if you want to use await for this function, then you should probably have the following:
getUsers(res) { // return promise so caller can get async value return User.findAll().then(users => { res.json(users); return users; // return value so caller can get access to the value }); }
Thus, the source code can be fine as long as the caller never expects an asynchronous return value from this function (which is possible here because the result of the async operation is sent with res.json() , and this may be the only result that required As for await / async, you only need to return a promise from the functions that you plan to use while waiting.
Repeat:
async is required only if you plan to use await inside a function. Perhaps your function doesn't need the async keyword at all.- A returned promise is only necessary if the caller wants to access the asynchronous response either through the traditional
f().then() or through let x = await f() . - The caller may
await function that is not marked as async . await will receive the return value from the function and, if the return value is not a promise, it ends it with a resolved promise. If this is a promise, it will be expected to be resolved.
FYI, this is a very nice, short and enjoyable overview of async / await and how they interact with promises.
source share