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?
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.
The async method can't declare any in, ref or out parameters, nor can it have a reference return value, but it can call methods that have such parameters.
Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized.
The await keyword can only be used inside functions that have the async tag. This also means that we cannot currently utilize it in the global scope. Since Node 10, we also have access to the promise. finally method, which allows us to run code regardless of whether the promise resolve or rejected.
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);
}
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
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 😊
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With