20

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?

11
  • 1
    Thats the best idea ever, I'm doing that all the time, thats what await is good for! Commented Oct 4, 2018 at 20:20
  • 1
    Just be to sure to handle promise (await) rejections... Commented Oct 4, 2018 at 20:21
  • @CodyG. and how does one handle promise (await) rejections? Commented Oct 4, 2018 at 20:22
  • i've done it: var pw=this.parseHex(await this.derive(password)); Commented Oct 4, 2018 at 20:22
  • 1
    Hmmm. New question: what happens when you call something like foo(await bar1(), await bar2()) ? I assume bar2 waits until bar1 but I'm too lazy to try and have never used that syntax Commented Oct 4, 2018 at 20:25

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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());
@ExplosionPills Yes, that's not in the async function, that's in the arrow function callback.
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

Comments

3

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 😊

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.