admin管理员组

文章数量:1417070

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',
        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();

}

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.',
        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();

}
Share Improve this question asked Oct 30, 2019 at 20:37 PKonstantPKonstant 9984 gold badges20 silver badges43 bronze badges 5
  • 2 you haven't wrapped your logic of setBattery in a promise. – Daniel A. White Commented Oct 30, 2019 at 20:39
  • ok. I have not used a promise before. – PKonstant Commented Oct 30, 2019 at 20:43
  • 2 async/await are tools that use promises, to understand async/await you need to understand promises. Also, adding async to a function definition changes the return type of that function to a promise, so you'll need to handle that promise. Something like exports.handler(a, b).then(() => {}).catch(() => {}).finally(() => {}) – JDunken Commented Oct 30, 2019 at 20:46
  • 1 "If I remove await/async, and make it synchronous, my function works correctly." Why do you want it to be async? – Jack Cole Commented Oct 30, 2019 at 20:57
  • 1 I am trying to add an http get call to our Alexa smart home skill lambda function and most of the code async. – PKonstant Commented Oct 30, 2019 at 21:40
Add a ment  | 

1 Answer 1

Reset to default 3

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.',
        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();

    });

}

本文标签: javascriptHow to awaitasync in a nodejs lambda functionStack Overflow