I am not asking about how to write the delay function because that question has been answered, I just doesn't understand the code itself.
I don't understand why we need to have a function returning another function?
How do we get the data
I have annotated the code with my comments.
If you run it in the console it should work. I am just looking for a newbie explanation for why do we need this currying syntax in here.
// a function
function delay(duration) {
// why do we return here !!
// this args are the data.json()
// but how do we have access to it?? I don't see anywhere in the code that we are calling delay(data => data.json())
// I know that .then calls the function for you with data.json() but that only if the function doesn't have a paramets for example doing just then(delay) but we are using a paramaeter here which is the 1000
return function(...args){
// so we return a new promise that resolves after sometime, this make sense.
// but I don't understand all these returns.
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(...args);
}, duration)
});
};
}
const endpoint = 'https://pokeapi.co/api/v2/pokemon/ditto/'
const prom1 = fetch(endpoint)
.then(data => data.json())
.then(delay(2000))
.then(console.log)