1

Recently I stumbled upon the Promise.then example on MDN just before this article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#nesting

The example uses this:

.then((url) =>
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        listOfIngredients.push(data);
      }), // Note this comma here
  )

In simple terms this is equivalent to the following:

.then(successFunc,);

To my surprise, this actually doesn't throw any error. Following works, but why?

const speakPromise = new Promise((resolve, reject) => {
    setTimeout(() => {        
        resolve("success");
    }, 500);    
});



speakPromise.then(function (data) {
    console.log(data, " End code");
}, ); // Note the trailing comma here
user31782
  • 7,087
  • 14
  • 68
  • 143

2 Answers2

0

The then function has the signature then(onFulfilled, onRejected).

The documentation says:

If one or both arguments are omitted or are provided non-functions, then they will be missing the handler(s), but will not generate any errors.

function f(...args) {
  console.log(args.length)
}
f(5)
f(6,)
f(7,8)

As you can see from the code above, a comma with no argument after it will be treated by javascript as if you'd simply not specified a second argument. Therefore, the presence or absence of a comma makes no difference when no argument follows it.

Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • Can you please add a link to the documentation. I found a related useful reference as well https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas#:~:text=Trailing%20commas%20(sometimes%20called%20%22final,already%20uses%20a%20trailing%20comma. – user31782 Dec 01 '22 at 06:31
  • @user31782 this is the doc I got it from https://devdocs.io/javascript/global_objects/promise/then – Andrew Parks Dec 01 '22 at 07:49
0

This is not related to .then(). Simply trailing commas are allowed in function calls:

console.log(1,);

This was added to the ECMAScript 2017 specification, section 12.3, syntax for arguments:

Arguments [Yield, Await]  :
    ( )
    ( ArgumentList [?Yield, ?Await] )
    ( ArgumentList [?Yield, ?Await] , ) 

The original proposal was proposal-trailing-function-commas by Jeff Morrison. The rationale was to allow more easily adding arguments in newlines without producing unnecessary noise in version control systems such as Git. Normally updating code like

finctionCall(
    "one",
    "two"
)

to add an argument would produce:

finctionCall(
    "one",
-   "two"
+   "two",
+   "three",
)

but with trailing commas the difference is much cleaner:

finctionCall(
    "one",
    "two",
)

updates to

finctionCall(
    "one",
    "two",
+   "three",
)

Moreover, there is no adverse effects to allowing fn(arg1,) and fn(arg1, arg2,) they are still treated as fn(arg1) and fn(arg1, arg2).

See also: MDN article on Trailing commas

VLAZ
  • 26,331
  • 9
  • 49
  • 67