简体   繁体   中英

Arrow function returning empty object then returns a function?

I've searched elsewhere for what's going on here but I can't find a similar example.

export const validateToken = (token) => () =>
  api.user.validateToken(token);

Is this saying export a function that takes an object that should be the token, then return nothing? And then call validateToken function but pass in the initial token object?

What is the difference between this and:

export const validateToken = (token) =>
  api.user.validateToken(token);

And why, if I remove the extra () and => do I get an error :

Error: Actions must be plain objects. Use custom middleware for async actions.


12 | 
  13 | componentDidMount() {
  14 |   // pass token from route
> 15 |   this.props.validateToken(this.props.match.params.token);
  16 | }
  17 | 
  18 | render() {

I am clearly missing something important here. Any and all help appreciated.

The function is actually returning another function. If you write it without the arrow syntax it might look a little more clear:

function validateToken(token){
    return function(){
        return api.user.validateToken(token);
    };
}

This is a common thing in functional programming. It's related to concepts like currying , where you partially apply parameters to a function to make new functions.

An example use would be something like:

let validate1=validateToken('abc');
validate1(); //=>output from api.user.validateToken('abc')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM