this snippet was extract from Ethan Brown´s book Learning JavaScript 3rd edition. Could someone explain, line by line if possible what exactly is happening on that function? Specially why are those functions beeing called using the spread operator? Couldn´t they just be called with no args at all?
function addTimeout(fn, timeout) {
if (timeout === undefined) timeout = 1000; // default timeout
return function(...args) {
return new Promise(function(resolve, reject) {
const tid = setTimeout(reject, timeout,
new Error("promise timed out"));
fn(...args)
.then(function(...args) {
clearTimeout(tid);
resolve(...args);
})
.catch(function(...args) {
clearTimeout(tid);
reject(...args);
});
});
};
}