Search code examples
javascriptsyntaxpromisearrow-functionschaining

ES6 Arrow Functions and Promise Chaining condensed syntax explanation


In the following code block, can someone please provide links or an explanation for the condensed alert statement syntax.

I understand the preceding expanded equivalent code that is commented out and contains the message parameter. However, I cannot find a reference to the syntax for omitting the message parameter:

      let timeoutPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('Success!');
        }, 2000);
      });

/*          timeoutPromise.then(message => {
                      alert(message);
                    }) 
*/        
       timeoutPromise.then(alert);

Solution

  • When you call .then(), it expects you to pass it a function reference and when that function is called, it will be passed one argument that is the resolved value of the promise.

    One way to do that is like this:

     somePromise.then(result => {
         console.log(result);
     });
    

    Here the function you are passing to .then() is an inline, anonymous, arrow function.

    But, you can also create a regular named function:

    function showMyValue(result) {
        console.log(result);
    }
    

    And, then pass it:

    somePromise.then(showMyValue);
    

    That's the exact same signature. You're passing a function reference and, when that function is called, that function expects one argument.

    Well, alert() is also a function that, when called, expects one argument so you can also do:

    somePromise.then(alert);