0

Hi so I have this piece of code that I want to run in order, however I always end up running the last line first and then the first one. Some guidance with this would be great.

    await fs.readFile(file, "UTF-8", (err, lines) => {
        lines = lines.split(/\r?\n/);
        lines.forEach( (line) => {
                line = line.split('\t');
                let book = new Book(line[0], line[1], line[2], line[3], 
                    line[4],line[5],line[6],line[7],line[8],line[9],
                    line[10],line[11]);
                console.log(book);
            }
        );
    });
    await pgdb.closeDatabase();

Close database looks like this

    closeDatabase = async() => {
        console.log("Closed")
        this.client.end();
    }

Thanks!

1 Answer 1

1

You are mixing callbacks and async/await

with callbacks, only the code inside the callback will execute after the file is retrieved. The control flow will immediately jump to the next line.

You are not awaiting anything.

try:

import fs from "fs/promises" //or require() 
// code...

const file = await fs.readFile(file, "UTF-8")

// do something with file contents

// do some more sync or async tasks

await pgdb.closeDatabase();
Sign up to request clarification or add additional context in comments.

2 Comments

What would I do if I want to use a async function with file? So instead of readFile I'm now using readFileSync and then split the result and for each result I try to run an async function but it's not working. Do you have any clue on how I could approach this?
Don't use readFileSync. Use readFile. Just make sure you are importing fs/promises instead of plain fs. That way, you use NO callbacks. You simply assign the value you await into a variable. This pauses the control flow until the filesystem call returns. As long as nothing is taking place in a callback, you are free to loop through the results of your call, (await) retrieving more data etc. If you are calling an async function and passing in file data, make sure the async function is returning a value. Simply await the function call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.