1

I'm wondering if there is any semantic difference between the 2 functions below in ES2017 or later:

async function returnBool() {
    const promise = new Promise(((res, rej) => {
        setTimeout(() => {
            res(true);
        }, 1000);
    }));
    // returns a boolean
    return await promise;
}

async function returnPromise() {
    const promise = new Promise(((res, rej) => {
        setTimeout(() => {
            res(true);
        }, 1000);
    }));
    // returns a boolean wrapped in a promise
    return promise;
}

I tested both versions on Node and they appear to behave the same. However, I'm looking for some assurances that both versions are syntactically and semantically correct.

In languages such as C#, there is always a discrepancy between the declared return type (Task<TResult>) and the actual return type in the body (TResult) in an async method. Judging from the example above, it seems to be not the case in Javascript? Could this suggest a lack of rigor with JS? What if I want to return a Promise<Promise<T>> from an async method? (unlikely, but still)

It would be really great if anyone could point to some docs or language standard to clarify this. Thanks!

scharnyw
  • 2,347
  • 2
  • 18
  • 32
  • 4
    Does this answer your question? [Difference between \`return await promise\` and \`return promise\`](https://stackoverflow.com/questions/38708550/difference-between-return-await-promise-and-return-promise) – joshwilsonvu Jun 23 '20 at 14:10
  • `async` functions always return a promise. There is no functional difference between an `async` function and a function returning a promise. The only thing `async` allows you to do is use `await`. So use the second implementation and drop `async`. – Felix Kling Jun 23 '20 at 14:11
  • use return promise. – Hexception Jun 23 '20 at 14:11
  • Josh Wilson yes its a duplicate – Hexception Jun 23 '20 at 14:11
  • 1
    "*What if I want to return a `Promise>` from an async method?*" That is not possible with promises, since they automatically and recursively flatten/join. If you have `new Promise(res1 => res1(new Promise(res2 => res2(42) )))` that simply a single level promise that produces `42` in the end. In many cases, that's fine, but whether it's completely correct [might be up for debate](https://stackoverflow.com/q/45770915). The advantage is some simplicity in chaining. The disadvantage is that sometimes you may want something more advanced. – VLAZ Jun 23 '20 at 14:37
  • @VLAZ I did not know that! Thanks a lot for the info! – scharnyw Jun 23 '20 at 15:20

1 Answers1

1

async functions always return a Promise. If you return a value that is not itself a Promise, it will be wrapped in a Promise and that Promise will be returned from the async function.

In second code example, you are explicitly returning a Promise which is unnecessary because, as mentioned above, async functions always return a Promise

Yousaf
  • 27,861
  • 6
  • 44
  • 69