7

Here's what I'm trying to do: I have a lambda function triggered by a webhook that will process that data and use it to make a POST request to an api.

I'm using Node.js 12 and the node-fetch module.

Right now the function is being triggered correctly, but it won't send the POST the first time it is called. But if I trigger the lambda function repeatedly in a short amount of time, the requests after the first will get through.

Here's the code in my lambda function's index.js file:

const fetch = require('node-fetch');

exports.handler = async (event) => {

    sendPost();

    const response = {
        statusCode: 200,
        body: "Ok",
    };

    return response;
};


function sendPost() {

    const url = "http://requestbin.net/r/vjv4mvvj";

    const body = {
        foo: "foo",
        bar: "bar",
        baz: "baz"      
    };

    const params = {
        method: "POST",
        mode: "cors",
        headers: {"Content-Type":"application/json"},
        body: JSON.stringify(body)
    };

    fetch(url, params);

}

When I delete the async in front of (event), then the request goes through the first time, but the server that sends the webhook in the first place doesn't get a response.

So basically I need the POST to send every time the function is called and also be able to return the 200 status code.

I don't have much experience working with async so I know it's related to that, but I'm scratching my head.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
benjfriedrich
  • 75
  • 1
  • 1
  • 6

1 Answers1

10

The fetch returns a promise, you need an await. Also you need to mark the sendPost function as async. You also need the handler function to wait for sendPost function to finish.

const fetch = require('node-fetch');

exports.handler = async (event) => {

    await sendPost();

    const response = {
        statusCode: 200,
        body: "Ok",
    };

    return response;
};


async function sendPost() {

    const url = "http://requestbin.net/r/vjv4mvvj";

    const body = {
        foo: "foo",
        bar: "bar",
        baz: "baz"      
   };

    const params = {
        method: "POST",
        mode: "cors",
        headers: {"Content-Type":"application/json"},
        body: JSON.stringify(body)
    };

    await fetch(url, params);
}
Arun Kamalanathan
  • 8,107
  • 4
  • 23
  • 39
  • 1
    By applying async/await to sendPost() it implicitly returns a promise. It would be more clear/concise to simply return the promise of fetch at the end of sendPost() instead of awaiting it inline. It is awaited for at the beginning of the handler.anyway. – i3ensays Apr 09 '20 at 02:56