AWS Lambda函数有两个回调

时间:2018-04-01 19:04:14

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

目前我正在node.js中做一个lambda函数来获取我的AWS账户的信息。当我想要检索函数中所需的信息时,我遇到了问题。我在控制台(console.log)中看到了这些信息,但是回调函数()中没有它。我总是得到第一次回调的反应,而不是第二回调。我已经阅读了有关异步过程但我没有解决问题的方法。你知道改进代码有什么变化吗?

代码是下一个:

var AWS = require('aws-sdk');
var iam = new AWS.IAM();
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
    var params1 = {};
 iam.listUsers(params1, function(err, data) {
   if (err)
    console.log(err, err.stack);
   else
    console.log(data);
    callback(null, data.Users);
 });
 var params2 = {};
 s3.listBuckets(params2, function(err, data) {
   if (err)
      console.log(err, err.stack);
   else
      console.log(data);
      callback(null, data.Buckets);
 });
};

提前致谢。

3 个答案:

答案 0 :(得分:3)

由于AWS Lambda现在支持节点8,因此可以在下面找到示例代码:

const AWS = require('aws-sdk');
const iam = new AWS.IAM();
const s3 = new AWS.S3();

async function stackoverflow() {
 let params1 = {};
 let params2 = {};

 try {
  // synchronously call each method and store resolved promises. 
  let results1 = await iam.listUsers(params1).promise();
  let results2 = await s3.listBuckets(params2).promise();

  console.log(results1);
  console.log(results2);
 }
 catch(e) {
  console.error(e);
 }
}

exports.handler = (event, context, callback) => {
  stackoverflow();
};

答案 1 :(得分:0)

如果你正在使用promises,这是Async库或Promise.all的理想情况。当我不在手机上时,我会尝试制作代码示例,但实际上他们都会让你执行多个异步功能,然后进行一次回调。

答案 2 :(得分:0)

使用Promise.all,您可以执行以下操作:

const AWS = require("aws-sdk");

const iam = new AWS.IAM({apiVersion: "2010-05-08"});
const s3 = new AWS.S3({apiVersion: "2006-03-01"});

exports.handler = (event, context, callback) => {
    const iamParams = {};
    const s3Params = {};
    const promises = [listUsers(iamParams), listBuckets(s3Params)];

    // NOTE: If any of the passed-in promises reject, `Promise.all` asynchronously
    // rejects with the value of the promise that rejected,
    // whether or not the other promises have resolved.
    Promise.all(promises)
        .then(([users, buckets]) => {
            // console.log(users);
            // console.log(buckets);
            callback(null, {
                Users: users,
                Buckets: buckets
            });
        })
        .catch((err) => {
            callback(err);
        });
};

function listUsers(params) {
    return new Promise((resolve, reject) => {
        iam.listUsers(params, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data.Users);
            }
        });
    });
}

function listBuckets(params) {
    return new Promise((resolve, reject) => {
        s3.listBuckets(params, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data.Buckets);
            }
        });
    });
}