Reputation: 145
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
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:
Upvotes: 3