2

Below is my code.

What I'm wondering is how to pass the data of the return parameter in the arrow function 'response' when passing the parameter to the variable 'ok'.

const response = (statusCode, formatter = null) => {
    const hasFormatter = typeof formatter === 'function';
    const format = hasFormatter ? formatter : _ => _;

    return (data = null) => {
        const response = {
            statusCode: statusCode
        };

        // Why is the data delivered??
        if (data) {
            response.body = format(data);
        }

        return response;
    }
};

const ok = response(200, JSON.stringify);

// Here, I put the parameter value({foo: 'bar'}) in the variable 'ok'.
console.log( ok({foo: 'bar'}) );
// {statusCode: 200, body: "{"foo":"bar"}"}
mi mi
  • 23
  • 2
  • I'm afraid it's not clear what you're asking. *"Why is the data delivered??"* Because you're calling that function and passing in an argument for the `data` parameter. – T.J. Crowder Jun 20 '19 at 07:09
  • Your code is working correctly. What is your desired outcome? – yqlim Jun 20 '19 at 07:11
  • What is the value of `Console.log(ok)` – Bosco Jun 20 '19 at 07:14
  • 1
    @T.J.Crowder First, I apologize for my poor English skills. you are correct. The function called reponse appears to have only two parameter values. Therefore, I thought that the parameter value named "data" in the return parameter can not be imported anywhere inside the "reponse" function, but it is not. – mi mi Jun 20 '19 at 07:19
  • @Bosco just return '[Function]' – mi mi Jun 20 '19 at 07:20
  • @YongQuan I know that code is not a problem. I just do not know why the parameter named 'data' is passed in the code below. – mi mi Jun 20 '19 at 07:22

1 Answers1

0

In a comment you clarified:

The function called reponse appears to have only two parameter values. Therefore, I thought that the parameter value named "data" in the return parameter can not be imported anywhere inside the "reponse" function, but it is not.

I see the source of your confusion. You're not calling response at the point you're getting data, you're calling the function it returns.

Here you're calling response and passing it arguments for both of its parameters:

const ok = response(200, JSON.stringify);

response returns a function, which you're remembering in the variable ok. The function ok, when called, uses the parameters you passed response and also its own parameter, data. (More on how it can use response's parameters in this question's answers and a dated post on my anemic little blog.)

So when you do this:

ok({foo: 'bar'})

you're calling the function response returned, passing in an argument for the function's data parameter.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875