Answer the question
In order to leave comments, you need to log in
How to deal with hanging promises?
Hello. Recently I encountered a situation where something synchronous in a promise freezes or loops, all asynchrony flies away. For an example illustrating this situation, I created 2 promises with synchronous loops that crap in the console. In the first promise, I provided a timer for the reject, which, by the way, will not work either.
The next question is how to deal with such situations?
code example:
const f1 = () => {
return new Promise((resolve, reject) => {
setTimeout(reject, 3000, "timeout");
while (true) {
console.log(1);
}
resolve(ture);
});
};
const f2 = () => {
return new Promise((resolve, reject) => {
while (true) {
console.log(2);
}
resolve();
})
};
f1();
f2();
Answer the question
In order to leave comments, you need to log in
Essentially your code boils down to this:
while (true) {
console.log(1);
}
and it doesn't come out of here. You need to wrap each iteration in a promise. I give an example in which there is an interesting point: the cycles alternate, but the timer is not called. If you figure out why, write.
async function asyncLog(items) {
console.log(items);
}
async function f1() {
setTimeout(() => {
throw Error("timeout");
}, 100);
while (true) {
await asyncLog(1);
}
}
async function f2() {
while (true) {
await asyncLog(2);
}
}
f1();
f2();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question