user2905256
user2905256

Reputation: 145

Why does my promise finish when ran once but not in a loop?

I am doing a project for fun where I am drawing to a canvas in node using pureimage, and then writing each animation frame to a separate png file.

If I run the below code once, it works as expected and creates a single PNG file.

If I put it in a loop, the promise never finishes. I think the existing process is being stopped and restarted because if I stop the program the PNG is corrupt.

So my question is, how can I run multiple promises in a loop, and where can I learn more about this issue?

PI.encodePNGToStream(img, fs.createWriteStream('img' + counter + '.png') ).then( function(){

  console.log("Wrote out file")

  counter = counter + 1

  console.log(counter)

}).catch( function() { 

  console.log("Error writing file")

})

Upvotes: 0

Views: 65

Answers (1)

Vinay Shrestha
Vinay Shrestha

Reputation: 266

When you are adding your code inside the loop, I think you were expecting it to work synchronously, right? But the thing is that promises are asynchronous in nature. The code inside the then runs when the promise is resolved.

What you could do is use async/await feature, but you need to wrap it inside a function with an async keyword before it like so:

async function test() {
    try {
        for(let counter = 1; counter < 10; counter++ ) {
            await PI.encodePNGToStream(img, fs.createWriteStream('img' + counter + '.png') );
            console.log("Wrote out file");
            console.log(counter);
        }
    } catch(e) {
       console.log(e.message);
    }
}

Check the following links for further details:

  1. https://javascript.info/callbacks
  2. https://javascript.info/promise-basics
  3. https://javascript.info/async-await

Upvotes: 3

Related Questions