5

The following emits an unhandledrejection event, but otherwise seems to "work".

for...await seems to respond to the rejected promise by emitting an exception (albeit after the first promise has resolved).

I can avoid the unhandledrejection event using Promise.all and Promise.allSettled. Is the following code an antipattern?

async function asyncFunction() {
    try {
        const happy = new Promise((resolve)=>setTimeout(()=>resolve('success'), 1000))
        const sad = new Promise((_,reject)=>setTimeout(()=>reject('failure')))
        const promises = [happy, sad]
        for await(const item of promises) {
            console.log(item)
        }
    } catch (err) {
        console.log(`an error occurred:`, err)
    }
}

asyncFunction()
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • Using a built-in statement is never an anti-pattern. It totally depends on how you use it and for what purpose. And at least the purpose of your script is not clear at all. – Andreas Mar 16 '20 at 11:38
  • 1
    All anti-patterns use "built-in statements", otherwise they wouldn't be valid code. – Ben Aston Mar 16 '20 at 11:42
  • Don't stop reading my comment after the first sentence ;) _**It totally depends on how you use it and for what purpose**. And at least the purpose of your script is not clear at all._ – Andreas Mar 16 '20 at 11:55
  • Something can not "never" be the case, and also at the same time "depend on how you use it". Your comment is logically inconsistent, but whatever. Meh. – Ben Aston Mar 16 '20 at 11:58
  • No reason for getting rude here... What would you call the [explicit construction (deferred) anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it)? Using `new Promise()` is good/bad/an anti-pattern? No. But using a new Promise that acts on another (implicit) Promise is an anti-pattern. – Andreas Mar 16 '20 at 12:16
  • Agree. But neither my question, nor my comments, asserted otherwise. The crux of my question is: "is this formulation of valid code, an anti-pattern, given that an uncaught error event can be emitted?" Seems a fair question. Even with six upvotes, you brigaded it to closed, meaning the people who want to know the answer are left hanging. – Ben Aston Mar 16 '20 at 12:18
  • I re-asked the question and got an answer here: https://stackoverflow.com/questions/60706179/using-for-await-of-with-synchronous-iterables#60707105. In short: yes it's an antipattern as-of ES2020. – Ben Aston Mar 16 '20 at 13:51

0 Answers0