简体   繁体   中英

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. 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 .

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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