NodeJS Async function called once only in a loop

Following is my code structure. I have two async functions from source.js and db.js. I’m exporting these functions and calling them in test.js.

test.js calls the function async loadFromFile() to read and return a list of json data elements. For every element in the list, it then calls async writeToDB().

Expected: N number of true in console

Result: Only 1 true output in console and only one element written to the database.

// source.js
async function loadFromFile() {
    const data = await fs.readFile('/path//to/.json', { encoding: 'utf8' });
    const ret = JSON.parse(data);
    return ret;
}
exports.loadFromFile = loadFromFile;
// db.js
async function writeToDB(data){
    console.log(data.length);    // THIS shows N data elements
    const query_str = "...";
    try{
        const response = await driver.executeQuery(query_str, ...);
        if (response){
            return true;
        }
   } catch(err){
        console.log('Error in query: '+ err);
   } finally {
        await driver.close();
   }
   // something went wrong
   return false;
}
exports.writeToDB = writeToDB;
// test.js
const source = require("./source")
const db = require("./db")

source.loadFromFile()
      .then(data_list => {
           console.log(data.length);    // This shows N data elements
           for (json_data of data_list){
                db.writeToDB(json_data)
                    .then(resp => console.log(resp))
                    .catch(error => console.error(error));
           }
    })
    .catch(error => console.error(error));

3

You are currently not awaiting the writeToDB calls inside the loop, and so time taken inside this loop isn’t going to get extended for the completion of these asyncops to finish execution.

Here is your test.js code corrected, waiting on each writeToDB call properly:

const source = require("./source")
const db = require("./db")

async function processFile() {
    try {
        const data_list = await source.loadFromFile();
        console.log(data_list.length);

        for (const json_data of data_list) {
            try {
                const resp = await db.writeToDB(json_data);
                console.log(resp);
            } catch (error) {
                console.error('Error writing to DB:', error);
            }
        }
    } catch (error) {
        console.error('Error loading file:', error);
    }
}

processFile();

Thanks to @”Daniel A white”, @Bergi and @”Bilal Azam”. Removing driver.close and calling the functions in their separate async-await solved the issue. The final code looks as follows

// source.js
async function loadFromFile() {
    const data = await fs.readFile('/path//to/.json', { encoding: 'utf8' });
    const ret = JSON.parse(data);
    return ret;
}
exports.loadFromFile = loadFromFile;
// db.js
async function writeToDB(data){
    console.log(data.length);    // THIS shows N data elements
    const query_str = "...";
    try{
        const response = await driver.executeQuery(query_str, ...);
        if (response){
            return true;
        }
   } catch(err){
        console.log('Error in query: '+ err);
   }
   return false;
}
exports.writeToDB = writeToDB;
// test.js
const source = require("./source");
const db = require("./db");

async function process() {
    const data = await source.loadFromFile();
    for (json_data of data){
        try {
            const resp = await db.writeToDB(json_data);
            if (!resp) {console.log('Error writing to DB');}
        } catch(err){console.log('Error:'+ err);};
    }
}

process()    
    .then(d => console.log(d))
    .catch(error => console.error(error));

Log output is as expected and all the data gets written to the DB as expected. However, the running node test.js on terminal gets stuck and never exits unless done manually using ctrl-c.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật