Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async await with setImmediate

Tags:

node.js

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?.

like image 969
Zakir saifi Avatar asked Feb 22 '19 14:02

Zakir saifi


1 Answers

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() {
}
  1. should return result into res
const res = await setImmediate(()=>{
     return readFile(filePath, 'UTF-8');
})
like image 94
Svitlana Avatar answered Dec 08 '22 18:12

Svitlana