I want to know the how to use setImmediate with async await and handle errors properly. I have written following code. But I am not sure it is adhering to the best practices.
There is a route in my express app
router.get('/parseinvoice', async (req, res, next) => {
    try {
        const parsedInvoiceResponse = await userhelper.getParseInVoiceList();
        res.json({parsedInvoiceResponse})
    } catch (error) {
        res.json({});
    }
});
The userhelper class code
 var userhelper = {};
const fs = require('fs'),
      path = require('path'),    
      filePath = path.join(__dirname, './input_user_story_12.txt');
const { promisify } = require('util')
const readFile = promisify(fs.readFile);
userhelper.getParseInVoiceList = async function() {
    return new Promise( async (resolve, reject) => {
        try {
            setImmediate(async function() {
                try {
                    const contents = await readFile(filePath, 'UTF-8');
                    resolve(contents);
                } catch (error) {
                    reject(error);
                }
            });
        } catch (error) {
           reject(error); 
        }
    });
}
module.exports = userhelper;
Although I am getting the response. I am not sure about the setImmediate part, whether the multiple try catch are required. Is there any neat way to write the below code?.
try {
    setImmediate(async ()=>{
        var res = await readFile(filePath, 'UTF-8');
    })
} catch(err) {
}
2.
await setImmediate(()=>{
       var res = await readFile(filePath, 'UTF-8');
}).catch(){}
3.
try {
    await setImmediate(()=>{
       await readFile(filePath, 'UTF-8');
    }).catch(){}
} catch() {
}
const res = await setImmediate(()=>{
     return readFile(filePath, 'UTF-8');
})
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With