Home > Net >  Why does Promise.prototype.then allow skipping reject function and allow comma at the end?
Why does Promise.prototype.then allow skipping reject function and allow comma at the end?

Time:12-01

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related