Reputation: 3039
Is it possible to use await with a parameter? for example:
const run = async () => {
getStudentDetails(await getStudentId());
}
Even if it is, it seems like it might not be the best idea. Anyone done this before?
Upvotes: 20
Views: 16237
Reputation: 2357
I do it all the time. However in case if you want to pass more than one parameter to function they will be resolved sequentially. To fight that problem I wrote an util function which looks like that:
async function call(func, ...args) {
return func(...await Promise.all(args));
}
(async function() {
console.log(await call(functionToCall, delay(2000), delay(2000)));
})();
With that syntax functionToCall will be called in 2 seconds instead of 4
Upvotes: 5
Reputation: 665364
Yes, you can use await
expressions in every arbitrary context (where it parses) inside the async function
, including as arguments to function calls. There's nothing wrong with it.
It's equivalent to
const run = async () => {
const studentId = await getStudentId();
getStudentDetails(studentId);
}
Upvotes: 15
Reputation: 150892
Yes, this will work, as you can use the await
keyword everywhere where you can use an expression.
However, I'd prefer a slightly updated version of your code for better readability (and for better debugability, too):
const run = async () => {
const studentId = await getStudentId();
getStudentDetails(studentId);
}
I hope this helps 😊
Upvotes: 3