Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how the better way to code nested callback?

I have 3 layer callbacks like this :

    app.post('/', (req, res) => {
        var filename = `outputs/${Date.now()}_output.json`;
        let trainInput = req.files.trainInput;
        let trainOutput = req.files.trainInput;
        let testInput = req.files.trainInput;

        //first
        trainInput.mv(`inputs/${req.body.caseName}/train_input.csv`, function (err) {
            if (err) return res.status(500).send(err);
            //second
            trainOutput.mv(`inputs/${req.body.caseName}/train_output.csv`, function (err) {
                if (err) return res.status(500).send(err);
                //third
                testInput.mv(`inputs/${req.body.caseName}/test_input.csv`, function (err) {
                    if (err) return res.status(500).send(err);

                    res.send('success');
                });
            });
        });   
    });

In this case, there are only 3 file uploads. In another case, I have more than 10 file uploads, and it makes 10 layer callbacks. I know it because of JavaScript asynchronous.

Is there any way, with this case, to make a beautiful code? This is because when it 10 layer callbacks, the code looks horizontally weird.

Thanks

like image 601
yozawiratama Avatar asked Jan 02 '23 06:01

yozawiratama


1 Answers

You can use the following code to make you code look better and avoid callback hell

app.post('/', async (req, res) => {
    var filename = `outputs/${Date.now()}_output.json`;
    let trainInput = req.files.trainInput;
    let trainOutput = req.files.trainInput;
    let testInput = req.files.trainInput;
    try {
        var result1 = await trainInput.mv(`inputs/${req.body.caseName}/train_input.csv`);
        var result2 = await trainInput.mv(`inputs/${req.body.caseName}/train_output.csv`);
        var result2 = await testInput.mv(`inputs/${req.body.caseName}/test_input.csv`);
        res.send('success');
    }
    catch (error) {
        res.status(500).send(error);
    }
});
like image 193
Andrew Rayan Avatar answered Jan 05 '23 16:01

Andrew Rayan