0
const axios = require("axios");
const Parser = require("./utils/parser");
const WebStore = require("./models/webstore");
const mongoose = require("mongoose");
require("./db/connection");
require("dotenv").config();

const url = "";
const app_secret = process.env.APP_SECRET;
const buff = new Buffer(app_secret);
const base64 = buff.toString("base64");
axios
  .get(url, {
    headers: {
      Accept: "application/json",
      Authorization: `Basic ${base64}`,
    },
    params: {
      from_date: "2020-02-19",
      to_date: "2021-02-21",
    },
  })
  .then(async (response) => {
    const data = response.data.split("\n");
    const events = [];
    data.forEach((point) => {
      try {
        const dat = Parser.toDB(JSON.parse(Parser.parser(point)));
        events.push(dat);
      } catch (err) {}
    });
    events.forEach(async (event) => {
      try {
        const e = new WebStore(event);
        await e.save();
        console.log("saved");
      } catch (err) {
        console.log("fail");
      }
    });
  })
  .catch((err) => {
    console.error(err);
  });


So After the execution the script outputs saved multiple times but the script is not closed itself.

The data is stored in the database after the execution I have tried mongoose.disconnect() and I've also tried mongoose.connection.close(). How do I resolve this issue ?

  • what is `WebStore`? can you post that code here? – Christian Fritz Feb 26 '21 at 20:43
  • 1
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – mehowthe Feb 26 '21 at 20:48
  • 3
    Never use `await` inside a `.forEach()` loop. Use a plain `for` loop instead. `.forEach()` is not `async` aware, thus you're just launching a bunch of parallel asynchronous calls with no control over it at all. – jfriend00 Feb 26 '21 at 20:49

0 Answers0