Get await function in loop to finish before script ends

Oct 14, 2021
Reaction score
Hello all,

I am having an issue where the script ends before finishing. Even the loop does not seem to finish as my consle.log to show each file name as the loop runs only shows the first two files before it stops.

I have a script I am working on that runs on node.js where I read files of a directory and then send them to a secondary module that performs some actions then it resolves then the script should move the file to another directory. For the mail function I am using async and await. I have the secondary module set a promise that resolves or rejects when finished or errored. As for the main script you can see below I use await in the for loop and a then process. The first files runs perfect then it looks like the second file starts and then it stops. I need some help pointing me to what I am doing wrong. I tested the script without the then and other function and the same thing happens so it has to be the script.

This is the output I see:
rawEDI (3).txt
Checking out
rawEDI (4).txt
Moved 'TestConnection\rawEDI (3).txt'->'orginalFile\rawEDI (3).txt_1634241613815.txt'

Here is the script file

const fs = require( 'fs' );
const path = require( 'path' );
const moveFrom = "./TestConnection";
const moveTo = "./orginalFile";
const errorLoc = "./Error"
const parse = require("./x12ParserModule.js");

const loadFiles = async () => {
try {
// Get the files as an array
const files = await fs.promises.readdir( moveFrom );

// Loop them all with for...of
for( const file of files ){
//get Time Stamp
let ts =;
var new_FileName = file + '_' + ts +'.txt';
// Get the full paths
const fromPath = path.join( moveFrom, file );
const toPath = path.join( moveTo, new_FileName );
const errorPath = path.join(errorLoc, new_FileName);
//parse.format is a promise and will resolve or reject
const parser = await parse.format(fromPath).then(value =>
{ moveFiles(value, fromPath, toPath, errorPath); });
} // End for...of
catch( e ) {
// Catch anything bad that happens
console.error( "RUNTIME ERROR", e );


const moveFiles = async (value, fromPath, toPath, errorPath) => {
// move async
await fs.promises.rename( fromPath, toPath );
console.log( "Moved '%s'->'%s'", fromPath, toPath );
else if(!value){
await fs.promises.rename( fromPath, errorPath );
console.log('Error In Parser');