【问题标题】:Nodejs, why lines after ASYNC call are not executing?Nodejs,为什么 ASYNC 调用后的行没有执行?
【发布时间】:2020-02-25 05:02:57
【问题描述】:

我正在尝试使用 Nodejs 编写 AWS Lambda 函数。

在代码中,我必须调用 API,等待响应并使用该数据执行其他操作(我还没有写任何关于此的内容) 注意:很抱歉将 customerTAX 声明为全局变量,但我更喜欢使用 lambda 函数,然后尝试从函数 isself 返回值。

这是代码:

'use strict';

var customerTAX;
const https = require('https');
const options = {
      host: 'xxxxxxx.com',
      port: 443,
      path: '/yyyyyyy.json',
      method: 'POST',
      headers: {
        'Content-Type': 'application/graphql',
      }      
};

exports.handler = async (event) => {

        const body = JSON.parse(event.body);
        const orderId = body.id;
        const customerId = body.customer.id; 
        console.log('ORDER ID: ' + orderId);
        console.log('CUST  ID: ' + customerId);
        const query = `xxxxxxxxxxxxxxxxxxxx`;

        //I CAN SEE ALL LOGS OF THIS FUNCTION IN CLOUDWATCH
        await getCustomerTAX(query);  
        //I CAN'T SEE NOTHING BELOW THIS LINE IN AWS CLOUDWATCH

        console.log('CUST TAX: ' + customerTAX);
        if (customerTAX != null) {
            console.log('LETs GO TO SAVE IT')
        } else {
            console.log('NOTAX: No customerTAX');
        }

        const response = {
            statusCode: 200,
            body: JSON.stringify(event.body),
        };          
        return response;
};

var getCustomerTAX = function(query) {
    return new Promise(function(resolve, reject) {
        var req = https.request(options, function(res) {  
            res.setEncoding('utf8');
            var bodyRaw = '';
            res.on('readable', function () {
                var chunk = this.read() || '';
                bodyRaw += chunk;
                console.log('getTAX CHUNK (' + Buffer.byteLength(chunk) + ' bytes): ' + chunk);
            });            
            res.on('end', function () {
                const body = JSON.parse(bodyRaw);
                if (body.TAX.value != null) {
                    customerTAX = body.TAX.value;
                } else {
                    customerTAX = null;
                }     
                console.log("getTAX END: " + customerTAX);
                resolve;
                //console.log('body: ' + Buffer.byteLength(body) + ' bytes');
            });
        });
        //handle the possible errors      
        req.on('error', function(e) {
            console.log("ERROR: " + e);
            reject(e);
        });
        //do the request
        req.write(query);
        //finish the request
        req.end();
    });
};

函数 getCustomerTAX 完美运行,但我不知道为什么我的 lambda 函数在这一行中“完成”了,而且我在 cloudwatch 中看不到更多控制台日志。

希望您的回答,非常感谢。

【问题讨论】:

  • 您的退货声明后有一个额外的},这是错字吗?
  • 是的,额外的}是一种类型,抱歉。我刚刚编辑了它

标签: node.js amazon-web-services asynchronous async-await aws-lambda


【解决方案1】:

对于getCustomerTax() 中的初学者,resolve; 需要为resolve();

这是一个函数。你需要调用它。

如果不调用resolve(),promise 永远不会被解析,因此await getCustomerTax() 永远不会完成,并且它后面的行永远不会被执行。


仅供参考,request-promise module 将自动执行您在 getCustomerTax() 中所做的很多事情(发出 http 请求、获取响应、处理所有可能的错误并返回代表结果的承诺)。


2020 年 1 月编辑 - request() 模块处于维护模式

仅供参考,request 模块及其衍生模块(如 request-promise)现在处于维护模式,不会积极开发以添加新功能。您可以阅读更多关于推理的信息herethis table 中有一个备选方案列表,其中对每个备选方案进行了一些讨论。我自己一直在使用got(),它从一开始就是使用 Promise 构建的,而且使用简单。

【讨论】:

  • 非常感谢,完美运行。现在我对这个问题有点尴尬,但非常感谢。我现在将尝试继续工作,希望不要有更多问题,但也非常感谢stackoverflow。
  • 关于request-promise,如果AWS Lambda函数Nodejs层有没有,我会有。 (我将不得不学习如何使用它)。可能我会继续使用这段代码,在我得到管理运行它没有任何问题后,我会尝试改进它。非常感谢。
  • @JuanRangel - request、request-promise 或 request-promise-native 库非常易于使用并且比您正在做的更简单。它们支持与http.get() 相同的所有选项,因为它们只是其上的一层。值得下次使用。他们甚至可以选择为您解析 JSON。他们实际上只是将您的所有代码更改为 return rp(options) 其中const rp = require('request-promise'); 然后返回值作为返回的承诺的解析值返回。
猜你喜欢
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2013-04-03
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
相关资源
最近更新 更多