【问题标题】:Node-Fetch Mapping Error - Cannot read property 'map' of undefined"节点获取映射错误 - 无法读取未定义的属性“映射””
【发布时间】:2019-11-09 20:18:19
【问题描述】:

当我尝试运行“地图”部分时出现错误无法读取未定义的属性“地图”

customers const 在上面声明,所以不确定。 undefined 来自哪里?地图需要声明吗?

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 呼叫没有 return 什么?
  • 顺便说一句,如果你的处理程序所做的只是重新抛出异常,你应该省略try/catch
  • 我猜你也想在map 调用的结果上使用return Promise.all(…)
  • Titus 答案已在上面添加,可能需要“return Promise...”,因为它当前正在返回一个 Promise 错误
  • @Gracie 你确定 fetch 会返回一些东西吗?您可以在网络面板中进行检查吗?另外(正如其他人所提到的)你不需要在前面等待 resp.json();sendEmailToCustomer(customer)

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


【解决方案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));

【讨论】:

  • …或者只是customers.map(sendEmailToCustomer)
  • 如果数组被扔掉,.map就没用了。
  • 我已将您的更改实施到我原来的问题中,我认为这是正确的方式,但仍然出现错误。 UnhandledPromiseRejectionWarning
  • @Gracie 这是警告而不是错误,这是因为您没有在承诺上调用 .catch 或将其添加到 try catch 中。
猜你喜欢
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 2018-01-07
  • 1970-01-01
  • 2021-08-31
  • 2017-05-21
相关资源
最近更新 更多