I attended a NodeJS coding interview. Our solution needs to lock the execution of a function if the update by ID is the same, but called from a different place (eg browser). Once the request is complete, the lock should be released and the next request should be allowed to execute.
No changes need to be made to the code below.
This will give an output below.
The expected answer:
Please note the comments in code "Don't change anything below". What would be the possible solution?
No changes need to be made to the code below.
JavaScript:
async function update(id, data) {
console.log(`start --> id:${id}, data:${data}`);
await randomDelay(); //update is happening here
console.log(`end --> id:${id}, data:${data}`);
}
//================================================= = ==============================
//================= Don't change anything below ========================= ======
//================================================= = ==============================
//---- update() is getting called from many places ----
update(1, "browser 1");
update(1, "browser 2");
//========================= Utility functions ======================= == ==============
//========================= Don't change any here================== = ===============
async function sleep(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), ms);
});
}
async function randomDelay() {
const randomTime = Math.round(Math.random() * 1000);
return sleep(randomTime);
}
This will give an output below.
JavaScript:
start --> id:1, data:browser 1
start --> id:1, data:browser 2
end --> id:1, data:browser 1
end --> id:1, data:browser 2
The expected answer:
JavaScript:
start --> id:1, data:browser 1
end --> id:1, data:browser 1
start --> id:1, data:browser 2
end --> id:1, data:browser 2