当我尝试运行“ map ”部分时出现错误无法读取未定义的属性“ map ””
上面声明了 customers
常量,所以不确定。 undefined 是从哪里来的? map 需要申报吗?
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
不返回任何内容,这意味着 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));
关于javascript - 节点获取映射错误 - 无法读取未定义的属性 'map'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56797312/