我应该何时使用圆括号来表示功能?

时间:2017-09-16 07:16:23

标签: javascript jquery function es6-promise

以下是my code

let cleanRoom = function() {
  return new Promise(function(resolve, reject) {
    resolve('Cleaned The Room');
  });
};

let removeGarbage = function(message) {
  return new Promise(function(resolve, reject) {
    resolve(message + ' remove Garbage');
  });
};

let winIcecream = function(message) {
  return new Promise(function(resolve, reject) {
    resolve( message + ' won Icecream');
  });
};

Promise.all([cleanRoom, removeGarbage, winIcecream]). then(function(){
    console.log('all finished');
})

Promise.all([cleanRoom(), removeGarbage(), winIcecream()]). then(function(){
    console.log('all finished');
})

如您所见,(带括号和不带括号)都会返回相同的结果。这是对的说法吗?

  

只有在想要将某些内容传递给函数时才应使用括号。否则无需使用它。

1 个答案:

答案 0 :(得分:4)

这就是区别:

  • 在第一个Promise.all上,您传递了对function的引用。

  • 在第二个Promise.all上,您正在传递对a的引用 Promise

如果您想记录结果,您会看到差异:

let cleanRoom = function() {
  return new Promise(function(resolve, reject) {
    resolve('Cleaned The Room');
  });
};

let removeGarbage = function(message) {
  return new Promise(function(resolve, reject) {
    resolve(message + ' remove Garbage');
  });
};

let winIcecream = function(message) {
  return new Promise(function(resolve, reject) {
    resolve( message + ' won Icecream');
  });
};

Promise.all([cleanRoom, removeGarbage, winIcecream]).then(function(result){
	console.log(result);
})

Promise.all([cleanRoom(), removeGarbage('foo'), winIcecream('bar')]).then(function(result){
	console.log(result);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

修改
我忘了提及,在某些功能中,您希望获得message参数 好吧,如果不使用括号,就无法通过它。