Home > Back-end >  Promise cause to stackoverflow with infinity while loop
Promise cause to stackoverflow with infinity while loop

Time:10-30

I am trying to understand why I am getting stackoverflow error following this code:

const promise = new Promise((res,rej) => {
    res(4);
})

while(true){
    promise.then((v) => v)
}

I am expecting to get

4
4
4
4
.
.
.

but get:

FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory

CodePudding user response:

I'm going to illustrate how you might create an infinite series of promises that doesn't have this problem, but warning: your tab will get stuck:

const pr = new Promise((res,rej) => {
    res(4);
});

(async () => {
  let promiseList = [];
  while(true){
    const p = pr.then((v) => console.log(v));
    promiseList.push(p);
    if (promiseList.length >= 20) {
       await Promise.all(promiseList);
       promiseList = [];
    }
  }
})();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Check your console and you'll see the 4s.

CodePudding user response:

Try using a loop inside of an async function like this as suggested below

async function someFunction(){
    while(true) {
        console.log(await promise);
    }
}
someFunction();
  • Related