E
E
Eugene2020-06-06 14:50:16
JavaScript
Eugene, 2020-06-06 14:50:16

How to make a function run asynchronously?

I want to move part of the logic into a separate function, but the main code does not want to wait for the file to be read... I tried several ways, but none of them work...

module.exports = async function(path) {
    await fs.readFile(`./server/db/${path}.json`, 'utf-8', (err, data) => {
        if (!err) {
            return data;
        }
    });
}


I tried to make a variable in the function and write data to it when received, but it flies away before the file is read ... and various asynchrony constructions - it doesn’t work ... I suspect that the problem is in the fs.readFile callback, but I can’t figure out how to outwit it ....
If needed, here is the code where I am trying to call this function....
server.get('/catalog', (req, res) => {
    reader('catalog')
        .then(data => {
            res.send(data);
        });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-06
@Kasperenysh

promisify

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question