10

I have the following code that checks the existance of a file and if present, parses the JSON data from it:

fs.access(dbPath, (err) => {
        if (err) throw err
        else{
            console.log('Database found. Processing data.');
            dbObj = processDatabaseFile(dbPath);
            console.log('checkonstartup: '+dbObj);
            return;
        }
    });

And here is the processDatabaseFile:

function processDatabaseFile(path){
    fs.readFile(path, (err, data) =>{
        if (err) throw err;
        let jsonData = JSON.parse(data);
        return jsonData;
    })
}

My problem is when the fs.access function is being called, it returns sooner than the processDatabaseFile(dbPath) returns. Eg. I want to make it use async await, but I don't know how to do that.

Tried putting async (err) => { ... declaration and then using dbObj = await processDatabaseFile(dbPath) but it gives errors around the if-else and semicolons and missing brackets.

Feedback is appreciated.

EDIT: About the errors regarding adding async-await. I was using VSCode and it turns out ESLint and JSHint conflicts each other.

VikingPingvin
  • 382
  • 5
  • 16

2 Answers2

16

You can make fat arrow function async using the syntax below.

const asyncFunc = async () => {
    const result = await someAsyncFunc();
}
bjupreti
  • 353
  • 3
  • 6
  • Does someAsyncFunc() in `await someAsyncFunc()` have to be really async? – VikingPingvin Apr 13 '19 at 13:35
  • @VikingPingvin Yes, it must return a promise – Bergi Apr 13 '19 at 13:36
  • 1
    No, `await`ed value can be just a value, `await 2 + 2` will amount to `4`. But if `someAsyncFunc()` is callback-based and doesn't return anything, then `await someAsyncFunc()` will be just undefined. You need to promisify it first. – mbojko Apr 13 '19 at 13:40
  • Oh yeah it expects a Promise to be returned from `someAsyncFunc()`. But, if `someAsyncFunc()` is not asynchronous I think there is no point in using `await`. – bjupreti Apr 13 '19 at 13:40
  • In my case it is, since it uses fs.readFile(), and I don't really want to make it blocking. – VikingPingvin Apr 13 '19 at 13:53
2

Promisify fs.readFile(), in Node you get promisify out of the box. Something like

const { promisify } = require('util');
const fs = require('fs');
const readFileAsync = promisify(fs.readFile);

fs.access(dbPath, async (err) => {
    if (err) throw err
    else {
        console.log('Database found. Processing data.');
        const dbObj = await processDatabaseFile(dbPath);
        console.log('checkonstartup: ' + dbObj);
    }
});

async function processDatabaseFile(path) {
    const data = await readFileAsync(path);
    return JSON.parse(data);
})
mbojko
  • 13,503
  • 1
  • 16
  • 26