Everything works great as long as I have "simple" layout with few text frames per page. With a lot of text frames per page the autoflowing takes a while, and it seems my script continues to run before the autoflowing is finished. The script tries to work on text not imported yet (or not placed on the pages yet) and it stops.
How can I wait for the place command and autoflowing to finish, before the rest of the script is executed?
Perhaps issue a document wide recompose, immediately after your "place" command?
Maybe a sledge hammer solution, but I think it's meant specially for cases like this. If it works, you can try if it works when you limit it to your newly placed Story -- that also has a recompose() method.
Excellent! It works great. I tried insertionpoint.recompose(), but it was obviously not enough.