ES6 Arrow Functions and Promise Chaining condensed syntax explanation

十年热恋 提交于 2020-06-17 15:53:31

问题


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);

回答1:


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);



回答2:


What is message => { alert(message); }? It's a function that takes one argument and, when called, will pop up an alert dialog.

Now, what is alert? It's a function that takes one argument and, when called, will pop up an alert dialog.

A foo => bar(foo) wrapper is almost always superfluous and equivalent to just bar.



来源:https://stackoverflow.com/questions/61682183/es6-arrow-functions-and-promise-chaining-condensed-syntax-explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!