Middle+
function delayFunc(fn, delay) { return function c(...args) { return new Promise((resolve) => { setTimeout(() => { fn(...args) }, delay * 1000) }) } } function sum(a, b) { console.log(a + b) } const delayedSum = delayFunc(sum, 5); await delayedSum(3, 2); // after 5 seconds, outputs 5 await delayedSum(5, 3); // after 5 seconds from the previous, outputs 8
sobes.tech AI
Answer from AI
In the provided code, the delayFunc function creates a wrapper around the passed function fn, which calls it with a delay of delay seconds.
However, in the current implementation, the Promise inside delayFunc does not call resolve, so await will never wait for its completion, and the delay will not work as expected.
The correct implementation should call resolve after executing fn, so that the promise completes:
function delayFunc(fn, delay) {
return function c(...args) {
return new Promise((resolve) => {
setTimeout(() => {
fn(...args);
resolve();
}, delay * 1000);
});
};
}
function sum(a, b) { console.log(a + b); }
const delayedSum = delayFunc(sum, 5);
(async () => {
await delayedSum(3, 2); // after 5 seconds, outputs 5
await delayedSum(5, 3); // after another 5 seconds, outputs 8
})();
Thus, calls to await delayedSum(...) will execute sequentially with a delay, as intended.