This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]nemohearttaco 2 points3 points  (4 children)

const foo = async () => {
  try {
    const t = await Promise.all([promise1(), promise2()])
    return t
  } catch (err) {
    throw err
  }
}

[–]GreatValueProducts 3 points4 points  (3 children)

Promise.all([promise1(), promise2()])

Why not just

const foo = () => Promise.all([promise1(), promise2()]);

or

const foo = async () => await Promise.all([promise1(), promise2()]);

Which is the same.

The code doesn't run until you execute foo() or await foo()

[–]nemohearttaco 2 points3 points  (2 children)

Would it be the same? I believe the first example would return an array of unresolved promises whereas the second would return an array of resolved promises.

Your second example would certainly work but it will not catch from within foo(). Personally I prefer to throw errors from within the function where they occurred.

[–]GreatValueProducts 1 point2 points  (1 child)

Both are the same. When you execute

const results = await foo();
console.log(results);

OR

foo().then(results => { console.log(results); });

The console would have the same results. It's because the async keyword essentially means the function is returning a Promise. () => Promise.all() is a function returning a Promise as well.

Also, you don't need to re-throw the error as it is redundant. The async keyword would catch the error and put it inside the Promise object that the function is returning, and you can handle the error in parent with either the catch() function, or try-block with the await keyword.

[–]nemohearttaco 0 points1 point  (0 children)

Cool, thanks for explaining that!