Answer the question
In order to leave comments, you need to log in
How would the event loop work in this situation?
Hello. What if the code gets to await.fetch() and at that moment the interval fires and deletes the array we are going to push data into after the asynchronous operation, we get 'Cannot read property 'push' of undefined'?)
const session = {
unanswered: [],
isRedirect: true,
date: 1545762010253
};
client.on('message', async (msg) => {
if (session.isRedirect) {
await fetch(...);
session.unanswered.push(msg.id);
} else {
session.isRedirect = true;
session.unanswered = [];
session.date = Date.now() + 60 * 1000;
}
});
setInterval(() => {
if (Date.now() > session.date) {
session.isRedirect = false;
delete session.unanswered;
}
}, 100);
Answer the question
In order to leave comments, you need to log in
const delay = ms => new Promise(res => setTimeout(res, ms));
const doAfterUnlock = async (session, func, ...args) => {
while (session.isBlock) {
// eslint-disable-next-line no-await-in-loop
await delay(1); // free event loop
}
try {
session.isBlock = true;
await func(...args);
} catch (e) {
console.error(e);
} finally {
session.isBlock = false;
}
};
As a matter of fact, it may not delete the array at all, but, as in the request, set it to empty.
if (Date.now() > session.date) {
session.isRedirect = false;
session.unanswered = [];
}
Perhaps something like this
const session = {
unanswered: [],
isRedirect: true,
date: 1545762010253
};
const intervalID = null;
const checkSession = () => {
if (Date.now() > session.date) {
session.isRedirect = false;
delete session.unanswered;
}
};
client.on('message', async (msg) => {
if (session.isRedirect) {
сlearInterval(intervalID);
await fetch(...);
session.unanswered.push(msg.id);
intervalID = setInterval(checkSession, 100);
} else {
session.isRedirect = true;
session.unanswered = [];
session.date = Date.now() + 60 * 1000;
}
});
intervalID = setInterval(checkSession, 100);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question