async
keyword JS-0376 62 }
63 };
64
65 const handleBulkMail = async (type: EmailType) => { 66 if (data !== null) {
67 const users = data?.data.users as ManagedUser[];
68 if (type === 'reminder') {
17 devMode: boolean,
18 res: VercelResponse,
19 emailT: EmailType
20) => { 21 const { firstName, email } = req.body;
22 let templateId;
23 switch (emailT) {
22 return null;
23};
24
25export const getUsers = async (token: string, filter?: string) => {26 let url;
27 if (filter) {
28 url = `${API_URL}/internal/users?status=${filter}`;
160 return null;
161}
162
163export async function verifyToken(token: string, queryClient?: QueryClient): Promise<boolean> {164 const url = `${API_URL}/auth/token/verify/`;
165 return axios({
166 method: 'POST',
218 return null;
219}
220
221export async function SignUp(user: NewUser) {222 return axios
223 .post(`${API_URL}/auth/registration/`, {
224 first_name: user.firstName,
A function that does not contain any await
expressions should not be async
(except for some edge cases
in TypeScript which are discussed below).
Asynchronous functions in JavaScript behave differently than other functions in two important ways:
Promise
.await
operator inside them.Functions are made async
so that we can use the await
operator inside them.
Consider this example:
async function fetchData(processDataItem) {
const response = await fetch(DATA_URL);
const data = await response.json();
return data.map(processDataItem);
}
Asynchronous functions that don't use await
might be an unintentional result of refactoring.
Note: This issue ignores async generator functions.
Generators yield
rather than return
a value and async
generators might yield all the values of another async generator without ever actually needing to use await
.
In TypeScript, one might feel the need to make a function async
to comply with type signatures defined by an interface.
Ideally, the code should be refactored to get rid of such restrictions, but sometimes that isn't feasible
(For example, when we are implementing an interface defined in a 3rd party library like Next.js).
This situation can easily be circumvented by returning the value with a call to Promise.resolve
:
interface HasAsyncFunc {
getNum: () => Promise<number>
}
// Not recommended:
const o: HasAsyncFunc = {
async getNum() { return 1 }
}
// Recommended:
const o: HasAsyncFunc = {
// We only use `Promise.resolve` to adhere to the type
// of the surrounding object.
getNum() { return Promise.resolve(1) }
}
It is also advised to add a comment near the redundant promise to make the intent clear.
async function promise1() {
return 1
}
async function fetchJSON(url: string) {
return axios.get(url)
}
function promise1() {
return Promise.resolve(1);
}
async function fetchJSON(url: string) {
const data = await axios.get(url)
return data.payload;
}