Should the caller function (CR) be declared with async
keyword and hence be an asynchronous function when the callee function (CE) is declared with async
keyword and is an asynchronous function? Assume that there is no other asynchronous task carried out by CR apart from calling CE but CR has some logic that depends on the response received from CE.
For example, I have an apiUtils.js
file which consists of a generic asynchronous function to make an API call. This function has the following signature:
export const sendApiRequest = async (apiParametersGoHere) => {
try {
const response = await axios(objectForAxiosAsParameter); // axios() can be replaced with fetch() or XMLHttpRequest(); the idea remains the same
// processing of response
} catch (error) {
// processing of error
}
}
I also have other files which import apiUtils.js
file to send specific API requests. For example, there's a userApi.js
file which imports apiUtils.js
and has a function named doLogin()
with the following signature:
export const doLogin = async (userLoginRelatedParameters) => {
try {
const response = await apiUtils.sendApiRequest(apiArgumentsGoHere);
// processing of response
} catch (error) {
// processing of error
}
}
Should the doLogin()
function be declared with the async
keyword and therefore be an asynchronous function? If yes, should all callers in the call stack be declared with async
keyword and therefore be asynchronous functions (assume another function F invoking doLogin()
function)? Why is it so?
P.S.: Please ignore determining the usage of async
keyword for doLogin()
function just based on the fact that the await
keyword is used inside the function body or try
/catch
blocks are used. The async/await
keywords are used for the purpose of demonstration only. You can also assume chaining of promises.