PKonstant
PKonstant

Reputation: 988

How to: await / async in a node.js lambda function?

I am trying to create an async lambda function that makes a http Get call put it's not working correctly and I believe it has to do with it being async. If I remove await/async, and make it synchronous, my function works correctly. I'm not sure what I am doing wrong. Thank you for your help!

exports.handler = async function (event, context) {

    await setBattery();

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

async function setBattery() {
    'use strict';

    const https = require('https');

    const options = {
        hostname: 'testsite.com',
        port: 443,
        path: '/proxy/api/setting?EM_OperatingMode=1',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    };

    const req = https.request(options, res => {
        console.log(`statusCode: ${res.statusCode}`);

        res.on('data', d => {
            process.stdout.write(d);
        });
    });

    req.on('error', error => {
        console.error(error);
    });

    req.end();

}

Upvotes: 0

Views: 9151

Answers (1)

ricardoorellana
ricardoorellana

Reputation: 2340

According with MDN Web Docs:

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

So, You need to return a Promise object in order to be handled by your async function (You could also use another promise to handle it), I converted setBattery to a normal function and the return of this function is now a promise that will be handled by your handler (exports.handler). I haven't tested the code but it should work.

exports.handler = async function (event, context) {

    await setBattery();

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

function setBattery() {
    'use strict';

    const https = require('https');

    const options = {
        hostname: 'testsite.com',
        port: 443,
        path: '/proxy/api/setting?EM_OperatingMode=1',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    };

    // Return it as a Promise
    return new Promise((resolve, reject) => {

        const req = https.request(options, res => {
            console.log(`statusCode: ${res.statusCode}`);

            res.on('data', d => {
                process.stdout.write(d);

                // If successful
                resolve(d);
            });
        });

        req.on('error', error => {
            console.error(error);

            // If failed
            reject(error);
        });

        req.end();

    });

}

Upvotes: 3

Related Questions