1

Is there any difference between

const foo = async () => {
  // some other code that uses await
  return await bar()
}

and

const foo = async () => {
  // some other code that uses await
  return bar()
}

Where bar is a function that returns a promise.

Is the await redundant or does it make any difference?

Vencovsky
  • 28,550
  • 17
  • 109
  • 176

3 Answers3

6

It is redundant.

It extracts the value from the promise returned by bar, and then resolves the promise returned by foo with it.

If you return bar's promise directly, then the promise returned by foo adopts it to the same effect.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    It is redundant in the sense that the result will be same if you call `foo().then(..)` or `await foo()`. However, I want to ask if the first approach is going to take more time at the `foo` function since you need to wait for the result of `bar()` before wrapping it in the returning Promise, whereas second approach just return the Promise of bar() directly without trying to resolve it (at least that's what it seems to me; I am uncertain) – Bao Huynh Lam Feb 10 '22 at 16:58
  • 3
    The first approach does not **wait** for the result of `bar()`. It's really the same thing in practical terms. JavaScript doesn't "wait". – Pointy Feb 10 '22 at 17:08
1

If the Promise is rejected, the error would be thrown in different places, in the two example you wrote.

In the first, a rejected error would happen inside foo.

In the second, a rejected error would happen to the function that called foo

Shani Kehati
  • 427
  • 5
  • 10
  • In my example, I don't think it would make any difference between throwing an error inside `foo` or by the function that called `foo`, it would only add one more function to a stacktrace, BUT if I had an try catch around that `return`, then it would make a difference right? Because it would be handled by `foo`'s try catch and not another from the function that called `foo` – Vencovsky Feb 10 '22 at 17:01
  • 1
    Yes I believe so. And abt the stacktrace, it's important in some (big) projects (: – Shani Kehati Feb 10 '22 at 17:25
-3

Yes.

If the function bar() returns a Promise, in the second case foo will return a pending Promise (a Promise that has not yet resolved). In the first case, foo will return the data the Promise resolved with after waiting for the Promise to resolve

marian150
  • 103
  • 5