Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an await in function parameter

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?

like image 971
Justin Avatar asked Oct 04 '18 20:10

Justin


People also ask

Can we use await in function?

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.

Can async functions have parameters?

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.

Can we use await for async function?

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.

Can we use await in callback function?

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.


3 Answers

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);
}
like image 108
Bergi Avatar answered Oct 26 '22 13:10

Bergi


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

like image 31
Kirill Reznikov Avatar answered Oct 26 '22 13:10

Kirill Reznikov


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 😊

like image 34
Golo Roden Avatar answered Oct 26 '22 12:10

Golo Roden