1
\$\begingroup\$

I have written an aws lambda function in NodeJS which has 2 async axios call.

var stripNS = require('xml2js').processors.stripPrefix;
parseString = require("xml2js").parseString;
const axios = require('axios');
let successflag = true;
let headers = {
'Content-Type': 'text/xml'
}

exports.handler = async (event, context, callback) => {
console.log("start");
let url = event.url;


var firstxmlRQ = '    <?xml version="1.0" encoding="utf-8"?>' +
    '<note importance="high" logged="true">' +
    '    <title>Happy</title>' +
    '    <todo>Work</todo>' +
    '    <todo>Play</todo>' +
    '</note>';

await axios({
    method: 'post',
    url,
    headers,
    data: xmlRQ,
}).then(result => {
    console.log(result)
    parseString(result.data, {
        tagNameProcessors: [stripNS]
    }, function (err, result) {
        //console.log(result)
        try {
            //...other operations
            successflag = true

        } catch (e) {
            successflag;
            callback(null, {
                error: "error"
            });

        }
    });
}).catch(err => {
    console.log(err);
});

if (successflag) {
    let secondxmlRQ = '<<?xml version="1.0" encoding="utf-8"?>' +
        '<note importance="high" logged="true">' +
        '    <email>xyz@gmail.com</title>' +
        '    <todo>Work</todo>' +
        '    <todo>Play</todo>' +
        '</note>';
    await axios({
        method: 'post',
        url,
        headers,
        data: secondxmlRQ,
    }).then(result => {
        console.log(result.data);
    }).catch(err => {
        console.log(err);
    });
}
   callback(null, {
    success: "success"
  });
}

I want to call the second axios only when the first one succeeds. I tried to make it to different functions but then the second function is not getting called properly. Right now I am getting the result but I would like to know an efficient way to handle multiple async axios.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.