18

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?

Justin
  • 2,940
  • 3
  • 25
  • 43

3 Answers3

15

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);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    And as long as you are in the same calling context as the async function, e.g. this doesn't work: `async () => fnTakingCb(() => await getStudentId());` – Explosion Pills Oct 04 '18 at 20:21
  • @ExplosionPills Yes, that's not in the async function, that's in the arrow function callback. – Bergi Oct 04 '18 at 20:22
5

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

Kirill Reznikov
  • 2,327
  • 3
  • 20
  • 27
2

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

Golo Roden
  • 140,679
  • 96
  • 298
  • 425