Search code examples
node.jsexceljs

Global variable not updated


I have a problem in this code.
I am trying to parse an excel file but cannot make the parent relationship.
Parent records are created successfully, child records are also created, but parent_id is always 0

    let parent_id = 0; // this var not updated!!!
    let workbook = new Excel.Workbook()
    workbook = await workbook.xlsx.readFile(location)
    workbook.worksheets[0].eachRow(async (row) => {
        console.log(parent_id) // each time 0,0,0,0
        const name = row.getCell(1).value
        const obj = {
            name,
            number: row.getCell(2).value,
            parent_id: name ? null : parent_id
        }
        if(obj.number && Number(obj.number) == obj.number){
            const node = await LeadNode.create(obj)
            if(name){
                parent_id = node.id
                console.log(parent_id) // work here 1,2,3,4,5
            }
        }
    });

db screen


Solution

  • The problem is caused by .eachRow() not awaiting for your callback to finish.

    If you somehow make the callback not async, it would work. This means that you'll have to call this await LeadNode.create(obj) outside the callback.

    Possible solution: create an array of obj, then iterate over them and call the await LeadNode(...). Something like:

    let parent_id = 0; // this var not updated!!!
    let workbook = new Excel.Workbook()
    workbook = await workbook.xlsx.readFile(location)
    const objs = [];
    workbook.worksheets[0].eachRow((row) => {
        console.log(parent_id) // each time 0,0,0,0
        const name = row.getCell(1).value
        const obj = {
            name,
            number: row.getCell(2).value,
        }
        objs.push(obj);
    });
    
    for (const obj of objs){
        if(obj.number && Number(obj.number) == obj.number){
            obj.parent_id = obj.name ? null : parent_id
            const node = await LeadNode.create(obj)
            if(name){
                parent_id = node.id
                console.log(parent_id) // work here 1,2,3,4,5
            }
        }
    }