0% found this document useful (0 votes)
2 views2 pages

Promise Riddle

The document defines a function 'x' that ensures a provided function can only run when not busy, returning a promise. Two functions, 'sleepAndLog' and 'sleepAndLog2', are created to log messages after a timeout. The usage of these functions demonstrates how the 'x' function manages concurrent calls, ensuring only one execution occurs at a time.

Uploaded by

pasaran460
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Promise Riddle

The document defines a function 'x' that ensures a provided function can only run when not busy, returning a promise. Two functions, 'sleepAndLog' and 'sleepAndLog2', are created to log messages after a timeout. The usage of these functions demonstrates how the 'x' function manages concurrent calls, ensuring only one execution occurs at a time.

Uploaded by

pasaran460
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

export function x(y) {

let isBusy = false;


let currentPromise;
return () => {
if (!isBusy) {
isBusy = true;
currentPromise = y()
[Link](() => (isBusy = false));
}
return currentPromise;
};
}

function sleepAndLog(timeout) {
return new Promise(resolve => {
setTimeout(() => {
[Link]("hello world");
resolve();
}, timeout);
});
}

function sleepAndLog2() {
return new Promise(resolve => {
setTimeout(() => {
[Link]("hello world 2");
resolve();
}, 2000);
});
}

sleepAndLog()
sleepAndLog() // both after 2s

let sleepAndLogFn; = x(sleepAndLog);


sleepAndLogFn();
sleepAndLogFn(); // both at 2
[Link]("This should print before hello world");

You might also like