0

So i have a IIFE as such in my code with a while loop inide. When the loop finished the console.log("Hey") executes but it doesnt come out of the function. Can anyone tell me whats going on?

(function () {
       return new Promise(async resolve => {
            while (i <= fcount) {
                i++;
                //some code
            }
            console.log("Hey");
            resolve("done");
       })
}());
Ashok
  • 369
  • 5
  • 16
  • What is the value of fcount? – some Apr 27 '19 at 16:54
  • 1
    "doesn't come out of the function" — what does that mean? How can you tell? What did you expect to happen? – Pointy Apr 27 '19 at 16:54
  • 1
    Where is `i` and `fcount` defined? – some Apr 27 '19 at 16:55
  • 2
    Why do you return a promise from an IEFE? And you should [never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Apr 27 '19 at 16:56
  • 2
    It looks like you are trying to make a `while` loop happen asynchronously. That's not going to work. – Mark Apr 27 '19 at 16:56

2 Answers2

-1

When you say

it doesn't come out of the function

Yes, it comes out of the function returning you a promise.

Just do something like this:

(function () {
       return new Promise(resolve => {
            while (i <= fcount) {
                i++;
                //some code
            }
            console.log("Hey");
            resolve("done");
       })
}().then(message => console.log(message)));

And you will get done in the console.

Another thing, why you use async you always need to use async with await.

You can do something like this:

async function whileFunc() {
  const message = await (function () {
       return new Promise(resolve => {
            while (i <= fcount) {
                i++;
                //some code
            }
            console.log("Hey");
            resolve("done");
       })       
  }());

  console.log(message);
}

calling whileFunc you will get message using async/await

F.bernal
  • 2,594
  • 2
  • 22
  • 27
-1

I wasn't closing the browser before returning (using puppeteer), hence the program kept running. Thanks everyone for your feedback.

Ashok
  • 369
  • 5
  • 16