I am a little bit confused with the code below. It’s obviously a two arrow function written in es6 code but I do not understand exactly some parts.
-
The 2nd parameter named
doneis an empty function that does nothing? Or it is executed with a simplereturnas the result from the second arrow anonymous function? -
the XXXX.load is a promise function that returns some results. How the caller of the
Indexcan get the results of the 2nd parameterdoneiedone(null, result)? -
What is the equivalent code in es5?
const Index = (name, done = () => {}) => (dispatch, getState) => {
return XXXX.load()
.then((result) => {
dispatch({type:OK});
done(null, result);
})
.catch((error) => {
dispatch({type:ERROR});
done(error);
});
};
>Solution :
- The empty function is a default value for
done. Default values prevents runtime crashes.
2 and 3 can be understood by seeing below code: (simply run it and see the consoles.
const DEFAULT_FUNCTION_VALUE = ()=> {};
const XXXX = {
load: function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({data: 'from XXXX.load'});
},2000);
});
}
}
const Index = function(name='', done=DEFAULT_FUNCTION_VALUE) {
return function(dispatch, getState) {
return XXXX.load().then(function(result) {
console.log({result});
done(result);
}).catch(function(error) {
console.log(error);
});
}
}
function doneImplementation(data) {
console.log('Data from done- ', data);
}
Index('', doneImplementation)();