最近我在这篇文章之前偶然发现了MDN上的
Promise.then
示例https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#nesting
示例使用这个:
.then((url) =>
fetch(url)
.then((res) => res.json())
.then((data) => {
listOfIngredients.push(data);
}), // Note this comma here
)
简单来说,这等同于以下内容:
.then(successFunc,);
令我惊讶的是,这实际上并没有抛出任何错误。以下作品,但为什么呢?
const speakPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
}, 500);
});
speakPromise.then(function (data) {
console.log(data, " End code");
}, ); // Note the trailing comma here
这与
.then()
无关。函数调用中只允许尾随逗号:
console.log(1,);
这已添加到 ECMAScript 2017 规范,第 12.3 节,参数语法:
参数[屈服,等待]: ( ) (参数列表[?产量,?等待]) ( ArgumentList [?Yield, ?Await] , )
最初的提案是 Jeff Morrison 的 proposal-trailing-function-commas。基本原理是允许更轻松地在换行符中添加参数,而不会在 Git 等版本控制系统中产生不必要的噪音。通常像
一样更新代码finctionCall(
"one",
"two"
)
添加一个参数会产生:
finctionCall(
"one",
- "two"
+ "two",
+ "three",
)
但尾随逗号的区别更清晰:
finctionCall(
"one",
"two",
)
更新到
finctionCall(
"one",
"two",
+ "three",
)
此外,允许
fn(arg1,)
和fn(arg1, arg2,)
他们仍然被视为fn(arg1)
和fn(arg1, arg2)
没有任何不利影响。
then
函数具有签名then(onFulfilled, onRejected)
.
文档说:
如果省略一个或两个参数或提供非函数, 那么他们将缺少处理程序,但不会生成任何 错误。
function f(...args) {
console.log(args.length)
}
f(5)
f(6,)
f(7,8)
正如您从上面的代码中看到的,后面没有参数的逗号将被 javascript 视为您根本没有指定第二个参数。因此,当后面没有参数时,逗号的存在与否没有区别。