-1

I am playing around with the mailchimp API. The code snippet adds a user to a mailing list and afterwards a success or failure message should be displayed. Unfortunaley I can't get a grasp on the status code .. It seems I get a different response in the case of adding a user successfully or not. If it was successfully I can access the status via response.statusCode but that doesnt work in a case of a failure:

const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
const https = require('https');
const mailchimp = require("@mailchimp/mailchimp_marketing");

const app = express();
//Includes local/static files
app.use(express.static('public'));
// Ads body parser and the function to read posted data
app.use(bodyParser.urlencoded({extended: true}));

mailchimp.setConfig({
  apiKey: "XXX",
  server: "us10",
});


app.get('/', function(req, res){
  res.sendFile(__dirname+'/sign_up.html');
});

app.post('/', async function(req, res) {

  //Audience ID
  const listId = 'XXX'

  const response = await mailchimp.lists.addListMember(listId, {
  email_address: req.body.email,
  status: "subscribed",
  merge_fields: {
    FNAME: req.body.firstName,
    LNAME: req.body.lastName
  }
});

  console.log(response.statusCode);


  if (response.statusCode == 200) {
    res.send(response.statusCode);
  } else {
    res.send(response.statusCode);
  }
})

app.listen('3000', function() {
  console.log('Hello World');
})

By the way, why is mailchimp using an async function?

Thank you for your support!

Best, Matthias

Dawienchi
  • 75
  • 1
  • 9

3 Answers3

1

You use an async keyword to make a function asynchronous.

async makes a function return a Promise

await makes a function wait for a Promise

Whenever you're using await in a function , you're supposed to make it asynchronous using async

Mohd Zaid
  • 117
  • 1
  • 10
0

I don't know if this is correct but it worked for me. I used the .then() method, you can learn more about it in the MDN docs

async function addMember() {
        const response = await mailchimp.lists.addListMember(listID, {
            email_address: email,
            status: "subscribed",
            merge_fields: {
                FNAME: firstName,
                LNAME: lastName,
            }
        }).then(
            (value) => {
                console.log("Successfully added contact as an audience member.");
                res.sendFile(__dirname + "/success.html");
            },
            (reason) => {
                res.sendFile(__dirname + "/failure.html");
            },
        );
    }

My code

0

There is nothing like (response.statusCode) in the object response you get from mailchimp.

Try:

console.log(response) 

It will show you, instead use response.status =='subscribed', it will work.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31