Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios in lambda not waiting for response

Tags:

axios

I am invoking axios post method in aws lambda. Most of the times lambda does not return any result.logs show the following results

START RequestId: ac92d268-d212-4b80-a06c-927922fcf1d5 Version: $LATEST END RequestId: ac92d268-d212-4b80-a06c-927922fcf1d5

But some times lambda return expected results. Looks like lambda is not waiting for axios to complete. below is lambda code.

var axios = require('axios')
exports.handler = async (event, context,callback) => {
    axios.post('https://example.com/testapi/api.asmx/GetNames', {})
    .then((res) => {    
      console.log(JSON.stringify(res.data,null,2))
      callback(null,'success');
    })
    .catch((error) => {     
      console.error(error)
      callback(null,'error');
    })    
 };
like image 365
user2184972 Avatar asked Mar 05 '19 11:03

user2184972


2 Answers

Your handler is async which means it will run asynchronously and return a Promise. This means that your function is being terminated before your code actually runs.

Since axios already works with Promises and your method already is async, you don't need to change too much. This will fix the problem:

const axios = require('axios')
exports.handler = async (event) => {
    try {
        const res = await axios.post('https://example.com/testapi/api.asmx/GetNames', {})
        console.log(res)
        return {
            statusCode: 200,
            body: JSON.stringify(res)
        }
    } catch (e) {
        console.log(e)
        return {
            statusCode: 400,
            body: JSON.stringify(e)
        }
    }
};

You can understand more around async/await if you want to.

like image 71
Thales Minussi Avatar answered Oct 09 '22 16:10

Thales Minussi


I was having a similar issue where I make a 3rd party API call with Axios in Lambda, after spending almost a day noticed that my lambda had 6 seconds default timeout. Sometimes the response from the api was getting longer than 6 seconds and it was causing a 502 response.

like image 26
Orhun Karapinar Avatar answered Oct 09 '22 14:10

Orhun Karapinar