简体   繁体   English

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

[英]Node-Fetch Mapping Error - Cannot read property 'map' of undefined"

Getting an error with the "map" part when I try and run it Cannot read property 'map' of undefined" 尝试运行它时,“地图”部分出现错误。无法读取未定义的属性“地图”

The customers const is declared above so not sure. 在上面声明了customers const,因此不确定。 Where is the undefined is coming from? 未定义的来源是什么? Does the map need declaring? 地图需要声明吗?

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);
  })
  );
})

getCustomers doesn't return anything which means that customers is set to undefined . getCustomers不返回任何内容,这意味着将customers设置为undefined

Try this: 尝试这个:

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;
  }
}

You also have to return something from the function that you pass as a parameter to .map 您还必须从作为参数传递给.map的函数中返回一些信息

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

or just: 要不就:

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

And since .map returns a new array (does not mutate the original array), you'll have to store the return value: 并且由于.map返回一个新数组(不改变原始数组),因此您必须存储返回值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM