I've just started getting accustomed with ES6 syntax and I was wondering if it was possible to assign to a variable with an arrow function. I'm writing a basic lightweight AJAX helper library and on a status of 200, I want to return a payload to the user, which I currently do with:
var responseData = "";
switch (payload.returnType.toLowerCase()) {
case "json" : responseData = JSON.parse(httpRequest.responseText); break;
case "text" : responseData = httpRequest.responseText; break;
default : responseData = null; break;
}
callback(null, responseData);
This is fine, but I can't help but think I could make this cleaner, if I do:
callback(null, () => { switch(payload.returnType.toLowerCase()) { ... });
I would expect the return
statement to send the result of the expression as the 2nd parameter in my callback, however when I console log from the caller it prints the switch statement.
Alternatively I have tried to do:
var responseData = () => {
switch (payload.returnType.toLowerCase()) {
case "json" : return JSON.parse(httpRequest.responseText); break;
case "text" : return httpRequest.responseText; break;
default : return null; break;
}
}
callback(null, responseData);
In this case, responseData
is always empty. Is it possible to have the return value as my 2nd parameter or have it bound to responseData
as the result of the arrow function?
callback(null, () => { switch(payload.returnType.toLowerCase()) { ... });
this will also work if you execute it like so:callback(null, (() => { switch(payload.returnType.toLowerCase()) { ... }));