节点提取映射错误-无法读取未定义的属性“地图”

时间:2019-06-27 19:06:41

标签: javascript arrays json async-await aws-lambda

在尝试运行它时,“ map”部分出现错误,无法读取未定义的属性'map'

上面已经声明了customers const,所以不确定。未定义的来源是什么?地图需要声明吗?

const AWS = require('aws-sdk'),
  ses = new AWS.SES(),
  fetch = require('node-fetch');

exports.handler = async (event) => {
  console.log(event.customer_id);

  const customers = await getCustomers();

  customers.map(async customer => await sendEmailToCustomer(customer));

  const customersEmailsPromises = customers.map(async customer => await sendEmailToCustomer(customer));

}

async function getCustomers() {
  try {
    const resp = await fetch('https://3objects.netlify.com/3objects.json');
    const json = await resp.json();

    return json;
  }
  catch(e) {
    throw e;
  }
}

const sendEmailToCustomer = (customer) => new Promise((resolve, reject) => {
  ses.sendEmail({
    Destination:
      { ToAddresses: [customer.email] },
    Message:
      {
        Body: { Text: { Data: `Your contact option is ${customer.customer_id}` } },
        Subject: { Data: "Your Contact Preference" }
      },
    Source: "sales@example.com"
  }, (error, result => {
    if (error) return reject(error);
    resolve(result);
    console.log(result);
  })
  );
})

1 个答案:

答案 0 :(得分:1)

getCustomers不返回任何内容,这意味着customers设置为undefined

尝试一下:

async function getCustomers() {
  try {
    const resp = await fetch('https://3objects.netlify.com/3objects.json');
    const json = await resp.json();

    return json;
  }
  catch(e) {
    throw e;
  }
}

您还必须从作为参数传递给.map的函数中返回一些内容

customers.map(async customer => {
    return await sendEmailToCustomer(customer);
});

或者只是:

customers.map(async customer => await sendEmailToCustomer(customer));

由于.map返回一个新数组(不改变原始数组),因此您必须存储返回值:

const customersEmailsPromises = customers.map(async customer => await sendEmailToCustomer(customer));