Is using await considered a bad practice in this situation?
P粉775723722
P粉775723722 2024-04-01 08:33:30
0
1
343

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粉775723722
P粉775723722

reply all(1)
P粉295728625

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 await What is the difference between Promise.all() and multiple awaits? 一个>.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!