search

Home  >  Q&A  >  body text

Is using await considered a bad practice in this situation?

I've seen several linters flag this behavior, but I'm wondering if that's not part of the reason you're using promises:

const promise = myFn()
//do other stuff
const result = myOtherFn(await promise)

Error: Promise should be awaited or captured

So is this a bad code? If so, why?

P粉775723722P粉775723722265 days ago456

reply all(1)I'll reply

  • P粉295728625

    P粉2957286252024-04-02 00:25:25

    Yes, this is an unusual use of await and a bad practice that can cause your application to crash.

    Usually you will immediately await the promise:

    const value = await myFn()
    // do other stuff
    const result = myOtherFn(value);

    The problem with not awaiting promises immediately is that you miss out when it rejects with an error while // do other stuff is running. If the other thing is async you may await too late, if the other thing itself throws the exception you never await it, in both cases this will Resulting in promise unhandled rejection, which will crash your application. See also Awaiting Multiple Concurrent Wait Operations and < a href="https://stackoverflow.com/questions/45285129/any-difference- Between-await-promise-all-and-multiple-await">await What is the difference between Promise.all() and multiple awaits? .

    reply
    0
  • Cancelreply