Javascript how the better way to code nested callback?

  • A+
Category:Languages

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

 


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);     } }); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: