2

I would like to understand the difference between the two code snippets, both resolving promises in different ways but receiving the same result (resolving after a second).

Which one is the right way?

function longTask(){
    return new Promise((resolve, reject) =>
    setTimeout(() => resolve(), 1000)
)}

longTask().then(() => console.log("done"));

function longTask(){
    return new Promise((resolve, reject) =>
    setTimeout(resolve, 1000)
)}

longTask().then(() => console.log("done"));
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • 3
    There's no difference in this case. – Barmar Sep 10 '21 at 16:22
  • They work the same. The only difference is not at all related to promises. You just pass a function reference to `resolve` in one case in the other an anonymous function that calls `resolve`. Promises are irrelevant for this. – VLAZ Sep 10 '21 at 16:23
  • 1
    For this scenario the only difference is an extra anonymous function that can be skipped. – Gabriele Petrioli Sep 10 '21 at 16:23

2 Answers2

2

Both are technically the same.

The first solution runs an anonymous function that calls the resolve.

The second solution gets a reference to the resolve function that gets called in the end as well.

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
2

In this case, where you're not resolving with a value, there is no difference. In situations where you need to resolve the promise with a value, you would want to use the first example so you can control what is passed into the resolve function.

function longTask(){
    return new Promise((resolve, reject) =>
    setTimeout(() => resolve(someResolvedValue), 1000)
)}

longTask().then(() => console.log("done"));

Edit: Or you can use the second example and pass the resolved value as the third argument to setTimeout. thanks to VLAZ for pointing this out.

function longTask(){
    return new Promise((resolve, reject) =>
    setTimeout(resolve, 1000, someResolvedValue)
)}

longTask().then(() => console.log("done"));
LazyElephant
  • 484
  • 2
  • 8