Error in Node-Fetch Mapping: Unable to access property 'map' of an undefined entity

Encountering an issue with the "map" section when attempting to run it - receiving an error message stating "Cannot read property 'map' of undefined"

The customers constant is defined above, so I'm unsure where the undefined value is originating from. Do we need to explicitly declare the map function somewhere?

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: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5320323f362013362b323e233f367d-3d303c3e">[email protected]</a>"
  }, (error, result => {
    if (error) return reject(error);
    resolve(result);
    console.log(result);
  })
  );
})

Answer №1

getCustomers function does not have a return value, so the variable customers is assigned as undefined.

Here is a suggested solution:

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

    return jsonData;
  }
  catch(error) {
    throw error;
  }
}

You must ensure that the function passed to .map returns a value.

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

Alternatively, you can simplify it to:

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

As .map creates a new array without modifying the original one, store the result in a variable:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

When utilizing CKEditor in conjunction with ExpressJS, HTML tags may be displayed in the browser

Check out my app.js code below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0> <meta http-equiv="X-UA-Compatible" content="ie= ...

Library for YAML or JSON with inheritance support

We are in the process of developing a new service that requires reading configuration settings from a file. Currently, we are utilizing both YAML and Jackson for deserializing the YAML data. One unique aspect of our project is that we need to have the abil ...

Traverse the depths of a nested JSON object and store its contents in an Android SQLite database

Here is a nested JSON Object I have: [ { "question_id":"1", "description":"What is your gender ?", "widget_id":"1", "answers":[ { "answer_text":"Male", "answer_id":"1" }, { "answer_text":"Female", ...

Updating a json file with PHP: Step-by-step guide to overwrite data

[ { "id" : 1, "name" : "levin", "description" : "some desc", "size" : "100KG", "actions" : { "walking" : true, "eating" : true } }, { "id" : 2, "name" : "clara", ...

Using Jquery to target an element within the same DOM element and apply changes

My website platform doesn't assign any IDs or classes to the menus it generates, and uses nested lists for submenus. To make the submenus expand upon clicking, I created a jQuery script: $(function () { $(".wrapper ul li").click(function () { ...

Exhibit MongoDB collection information through PUG template (Issue: Undefined Array)

I am encountering an issue while attempting to showcase the data from my MongoDB "users" collection. I keep receiving an undefined error with the array. Within my user controller file, I have imported express, express.router, and my user model. Below is ...

When I implement the persist gate in Next.js with Redux, the flex direction automatically adjusts

I'm currently developing an app using next js and redux. An interesting issue has arisen - when I include PersistGate in my _app.js file, the flex direction mysteriously changes from row to column in index.js. There haven't been any modifications ...

Managing error responses while fetching a blob through AJAX

Is it possible to execute an AJAX call that has the potential to return either a blob or a text string based on the server's response? My current task involves using AJAX to transform a user-provided video into an audio blob that can be utilized with ...

Encountering Timeout Issues with Reading Streams on Amazon S3 using Express.js

I am currently facing an issue with streaming videos from an Amazon S3 Bucket. It seems that everything works perfectly when calling my REST endpoint once, but the problem arises when trying to stream the video simultaneously from multiple browsers. The er ...

Add some flair to your list by animating the text within it

My goal is to add animation to the text within the list. Below is the code snippet: <div id="about" class="row section"> <div class="col-sm-8"> <h2 style="color:black;">About me!</h2> <ul> <li > ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...

Purging information from JavaScript object

Looking for a way to remove just one piece of data from a JavaScript object in my React app. Here's the structure of the object: state = { data: [] } const contactData = { Datas: { name: "william", email: "<a href="/cdn-cgi/l/email-pr ...

How to access the final element in a JSON document stored in a Blob Storage system

If I need to access the last element of a json file for an Azure blob aggregation test, one option is to download[toStream] the entire file and validate the last element. However, I am curious if there is a more efficient method to achieve this without d ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Dealing with excessively large data for json_encode in PHP

In my Symfony project, I am facing an issue while trying to retrieve database data through AJAX. Specifically, when attempting to json_encode all estimates from our database (over 60k in total), I encounter an out of memory error. Interestingly, if I try t ...

Facing issues with ng-options duplication?

I have provided the code below that I would like to display: $scope.states="India"; $scope.cities="Madhya Pradesh"; $scope.city="Ajmer"; When attempting to implement this in a cascading dropdown format, I encountered an error. You can find my jsfidd ...

An asynchronous function does not provide a result

As a beginner in the realm of Javascript, I find myself challenged by a task involving reading multiple files and constructing a JSON object response. While I have managed to execute most of the code successfully, I am stuck at the final hurdle - receiving ...