async function
should have await
expression JS-0116async
function without any await
expressions146 </>
147 )
148}
149export const getStaticPaths: GetStaticPaths = async () => {150 return {151 paths: [],152 fallback: 'blocking',153 }154}155export const getStaticProps = async ({
156 params,
157 locale,
async
function without any await
expressions 5
6import { type TGetParentNameSchema } from './query.getParentName.schema'
7
8const getParentName = async ({ input }: TRPCHandlerParams<TGetParentNameSchema>) => { 9 const { slug, orgLocationId } = input1011 switch (true) {12 case Boolean(slug): {13 return prisma.organization.findUniqueOrThrow({14 where: { slug },15 select: { name: true },16 })17 }18 case Boolean(orgLocationId): {19 return prisma.orgLocation.findUniqueOrThrow({20 where: { id: orgLocationId },21 select: { name: true },22 })23 }24 default: {25 throw new TRPCError({ code: 'BAD_REQUEST' })26 }27 }28}29export default getParentName
async
function without any await
expressions 3
4import { type TGetNameFromSlugSchema } from './query.getNameFromSlug.schema'
5
6const getNameFromSlug = async ({ input }: TRPCHandlerParams<TGetNameFromSlugSchema>) => { 7 const result = prisma.organization.findUniqueOrThrow({ 8 where: { 9 slug: input,10 },11 select: {12 name: true,13 },14 })15 return result16}17export default getNameFromSlug
async
function without any await
expressions 3
4import { type TGetAllForRecordSchema } from './query.getAllForRecord.schema'
5
6const getAllForRecord = async ({ input }: TRPCHandlerParams<TGetAllForRecordSchema, 'protected'>) => { 7 const results = prisma.internalNote.findMany({ where: input }) 8 return results 9}10export default getAllForRecord
async
function without any await
expressions 4
5import { type TServiceModalSchema } from './query.serviceModal.schema'
6
7const serviceModal = async ({ ctx, input }: TRPCHandlerParams<TServiceModalSchema>) => { 8 try { 9 return null10 } catch (error) {11 handleError(error)12 }13}14export default serviceModal
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 fetchData(): string {
// `readFileSync` is a synchronous function that blocks
// the main thread, and thus does not need to be `await`ed
return fs.readFileSync("data.txt", "utf-8");
}
performAction(async () => { console.log("no awaits in here") });
async function fetchDataAsync(): Promise<string> {
return await fs.readFile("data.txt", "utf-8")
}
performAction(async () => { await writeToFile(data) });
// Allow empty functions.
async function no_op() {}