在AWS Lambda上列出Cognito用户池的用户

4
我正在尝试在我的Lambda函数中列出所有Cognito用户,但是返回值为空,就好像回调函数没有被执行。我做错了什么?
下面代码的输出只会在控制台上显示一个“hello”。
var AWS = require("aws-sdk");

const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
export async function main() {
console.log("hello")
  var params = {
    UserPoolId: "myuserpoolid",
    AttributesToGet: ["username"]
  };

  cognitoidentityserviceprovider.listUsers(params, (err, data) => {
    if (err) {
      console.log(err, err.stack);
      return err;
    } else {
      console.log(data);
      return data;
    }
  });
}

1
尝试在您的函数中删除async关键字。 - junwen-k
2个回答

4
首先,代码结构有误。Lambda函数的头部应该有一定的结构,可以使用异步函数或非异步函数。因为在您的示例中使用的是非异步代码,所以我将向您展示如何使用后者。
var AWS = require("aws-sdk");

const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();

exports.handler =  function(event, context, callback) {
  console.log("hello")
  var params = {
    UserPoolId: "myuserpoolid",
    AttributesToGet: ["username"]
  };

  cognitoidentityserviceprovider.listUsers(params, (err, data) => {
    if (err) {
      console.log(err, err.stack);
      callback(err)        // here is the error return
    } else {
      console.log(data);
      callback(null, data) // here is the success return
    }
  });
}

在这种情况下,Lambda 仅在调用 callback(或超时)时才会结束。
同样,您可以使用异步函数,但需要相应地重新构造代码。以下是从 官方文档 中获取的示例。请注意如何使用 promise 包装器。
const https = require('https')
let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"

exports.handler = async function(event) {
  const promise = new Promise(function(resolve, reject) {
    https.get(url, (res) => {
        resolve(res.statusCode)
      }).on('error', (e) => {
        reject(Error(e))
      })
    })
  return promise
}

0

在AttributesToGet中,不要使用username,因为它是始终返回的字段之一。以下是Attributes数组的成员,并可用于AttributesToGet字段:

sub,email_verified,phone_number_verified,phone_number,email。

例如:

AttributesToGet: ["email","email_verified"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接