V
V
Vitaly2017-02-02 14:12:44
JavaScript
Vitaly, 2017-02-02 14:12:44

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();

The console will fly to infinity -> 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2017-02-09
@vshvydky

Essentially your code boils down to this:

while (true) {
    console.log(1);
}
and it doesn't come out of here.
And if in more detail, then:
1. When f1() is called, its code starts executing immediately in the same eventloop (i.e. synchronously)
2. setTimeout we only plan to put a function in the macrotask for execution in 100 ms. And this is one of the following event loops.
3. We fall into an endless while and we don’t exit from here.
See this article Tasks, microtasks, queues and plans if you want to understand. Unfortunately the original Tasks, microtasks, queues and schedules are not available. There was a cool interactive example.
In fact, calling an asynchronous function is equivalent to creating a promise.
What you wanted to do in the example is not entirely clear.

V
Vitaly, 2017-02-02
@vitali1995

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 question

Ask a Question

731 491 924 answers to any question