簡體   English   中英

如何:在 node.js lambda function 中等待/異步?

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

我正在嘗試創建一個異步 lambda function 使http Get call put it's not working normal 我相信它與異步有關。 如果我刪除await/async並使其同步,我的 function 工作正常。 我不確定我做錯了什么。 謝謝您的幫助!

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

}

根據 MDN Web 文檔:

async function 聲明定義了一個異步 function,它返回一個 AsyncFunction object。 異步 function 是 function 通過事件循環異步操作,使用隱式 Promise 返回其結果 但是使用異步函數的代碼的語法和結構更像是使用標准同步函數。

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由您的處理程序( exports.handler )處理。 我還沒有測試過代碼,但它應該可以工作。

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

    });

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM