Are there differences between .then(functionReference) and .then(function(value){return functionReference(value)})?

前端 未结 4 1419
深忆病人
深忆病人 2020-12-01 18:35

Given a named function utilized to handle a Promise value

function handlePromise(data) {
  // do stuff with `data`
  return data
}
4条回答
  •  醉话见心
    2020-12-01 19:08

    It is possible to create a case where there is a difference when no argument is passed, but it is a stretch and generally you should pass f and not function(x) { return f(x); } or x => f(x) because it is cleaner.

    Here is an example causing a difference, the rationale is that functions that takes parameters can cause side effects with those parameters:

    function f() {
       if(arguments.length === 0) console.log("win");
       else console.log("Hello World");
    }
    const delay = ms => new Promise(r => setTimeout(r, ms)); // just a delay
    delay(500).then(f); // logs "Hello World";
    delay(500).then(() => f()) // logs "win"
    

提交回复
热议问题