代码之家  ›  专栏  ›  技术社区  ›  Private

为什么我的lambda只在我回电话时才起作用?

  •  -1
  • Private  · 技术社区  · 6 年前

    const AWS = require( 'aws-sdk' );
    var FIREhose = new AWS.Firehose();
    exports.handler = async (event,context,callback) => {
        // TODO implement
        const response = {
            statusCode:200,
            Name:event.Name,
            Value:event.Value
        };
    const params = {
      DeliveryStreamName: 'kinesis-firehose', 
      Record: { Data: new Buffer(JSON.stringify(response)) }
    };
    
    FIREhose.putRecord(params, (err, data) => {
    if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);
    });
    };
    

    以下是我的活动

    {
      "Name": "Mike",
      "Value": "66"
    }
    

    当我运行这个lambda时,我得到的响应是 null 但当我加上 callback(null,"success") 像这样排在最后

    FIREhose.putRecord(params, (err, data) => {
    if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);
    });
    callback(null,"success")
    };
    

    我看到数据被推送到了S3。为什么? 做 async 有什么需要帮忙的吗? 谢谢

    1 回复  |  直到 6 年前
        1
  •  3
  •   thomasmichaelwallace    6 年前

    exports.handler = async (event,context,callback) => {
      // code goes here.
    
      await FIREhose.putRecord(params).promise();
      return null; // or whatever result.
    };
    

    使用回调方法:

    exports.handler = (event,context,callback) => {
      // code goes here.
    
      FIREhose.putRecord(params)
        .promise();
        .then((data) => {
          // do stuff with data.
          // n.b. you could have used the cb instead of a promise here too.
          callback(null, null); // or whatever result.
        });
    };
    

    (还有第三种方法 context. 但这是一个错误

    这一切都是由于lambda如何工作,并检测何时有响应。

    undefined )所以没有什么可等待的,它会立即返回-很可能在putRecord调用完成之前。

    当你使用 callback 不过,你明确告诉lambda你用的是“旧”方式。有趣的是 回拨 完成节点的事件循环(默认情况下)。也就是说 .putRecord