0

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);
                });
        });
    };
}
user3682983
  • 177
  • 2
  • 14
  • This is off topic for Stack Overflow. This site is for debugging specific problems to reach a goal, not discussion or explaining. You should take this to a chat or forum, or maybe softwareengineering.stackexchange.com (although I'm not entirely sure if it's on topic there). Good luck! – Goose Feb 14 '17 at 22:22
  • 2
    Well, what can I say? This is horrible code. – Bergi Feb 14 '17 at 22:25
  • line 1, declares a function ... line 18, end of the function ... lines 2 to 17 - absolute garbage that you would be better to disregard if you want to use javascript – Jaromanda X Feb 14 '17 at 22:27
  • 1
    Not all of those `...` s are `spread` operator, some are `rest` operators. And... judging from this example code i think you best throw away that book. – Redu Feb 14 '17 at 22:28

0 Answers0