Reputation: 9839
Do all functions in an async/await
chain have to use the async/await
keyword?
async function one() {
return await fetch(.....);
}
async function two() {
return await one();
}
async function three() {
return await two();
}
I've seen some examples in tutorials where the caller doesn't have to use the keyword.
Upvotes: 4
Views: 2585
Reputation: 370769
No, at least not for this example - if you have a function that is just await
ing a Promise and return
ing the result, you can just return that Promise alone, without any async
or await
:
function one() {
return fetch(.....);
}
function two() {
return one();
}
function three() {
return two();
}
If you want to have a flat function body, you would need to use await
when that function consumes a Promise and needs to do something else before returning another resolved Promise to the caller. For example:
async function one() {
const fetchResult = await fetch(.....);
// do something with fetchResult
return foo;
}
function two() {
return one();
}
function three() {
return two();
}
Here, one
is await
ing the fetch
call, and doing something with it afterwards before returning a Promise, but two
and three
don't need to be async
because, again, they're just calling a function that returns a Promise and returning that Promise to the caller. If two
or three
also had to do something after waiting but before resolving, then they would have to use await
(if you wanted a flat function body):
async function one() {
const fetchResult = await fetch(.....);
// do something with fetchResult
return foo;
}
async function two() {
const oneResult = await one();
console.log('got result for one');
return oneResult;
}
function three() {
return two();
}
Upvotes: 6