What issues are present in these function invocations in Node.js?

I encountered an issue with my functions for importing data from a JSON file into the database. When I tried calling the importData function alone, it didn't work. However, when I called deleteData first and then importData, the database ended up empty.

 const tours = JSON.parse(
  fs.readFileSync(`${__dirname}/tours-simple.json`, 'utf-8')
);


const deleteData = async () => {
  try {
    await Tour.deleteMany();
  } catch (error) {
    console.log(error);
  }
};

//Importing data into the database
const importData = async () => {
  try {
    await Tour.create(tours);
    console.log('Successfully loaded data!');
  } catch (error) {
    console.log(error);
  }
};

deleteData();
importData();

Answer №1

The two functions do not run synchronously, although they are inside a synchronous block. To ensure they run in the desired order, you can enclose them in an Immediately Invoked Function Expression (IIFE):

(async () => {
   await deleteData();
   await importData()
})()

Alternatively, you can use .then():

deleteData().then(importData).then(()=>console.log('done'))

The use of async indicates that the function returns a promise, so it should be treated as such.

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

Chrome triggers Skrollr 'relative top-bottom' animations prematurely

I am working with multiple relative positioned divs stacked on top of each other, each set to a height of 100% using jQuery upon loading. Within these relative positioned divs, there is a fixed div containing the content. Using skrollr, I have implemented ...

Error in the syntax containing ?callback=jQuery1113

I'm attempting to initiate a simple JSONP query: <html> <head> <script type="text/javascript" src="js/jquery1.js"></script> <script> $(document).ready(function(){ $.ajax({ ...

Deactivate a function within Bootstrap JavaScript

Is there a way to temporarily disable a function within Bootstrap after a click event? <a href="#"><span class="glyphicon glyphicon-triangle-right" id="btn04" onclick="myfun();"></span></a> Additionally, I am looking for a soluti ...

How can I send a value from a for loop to a URL within a modal using Django?

Currently, I am working on a project that involves using a for loop with buttons and their corresponding pk values. {% for obj in all_objects %} <button data-toggle="modal" data-id="{{ obj.pk }}" data-target="#myModal" class="open-my-modal"> {{ ob ...

Determining the height of child elements within a React component

One challenge I'm facing inside a React component is the need to calculate the total height of my child containers, specifically the three h3 elements, in order to accurately determine the height of my parent div during a transition animation. While I ...

Postgres error in NodeJS: Cannot resolve address - ENOTFOUND

My connection string for accessing my AWS database is pg://user:pass@localhost:port/table. It works perfectly fine when connecting to localhost, but as soon as I attempt to connect to the AWS server, everything falls apart. Even a simple connection code r ...

What causes the text field and checkbox to move downward as I enter text?

I'm currently working on a mock login page using React and Material UI. I implemented a feature where the show/hide password icon only appears when the user starts typing in the password field. However, after making this change, I noticed that the pas ...

Tracking and monitoring the advancement of multiple ajax post requests

Currently, I am utilizing jQuery for multiple ajax POST requests. In order to effectively manage the success or failure of each request and track the overall progress of the entire batch, my goal is to update the UI with a progress bar and information on t ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

The process of sharing information between JavaScript classes

I'm struggling to grasp the concept of object-oriented JavaScript, particularly in terms of how classes can communicate with each other. Let's consider an example using Babel: We have a "ColorPalette" class that contains a list of colors We also ...

Enhance precision with autofocus feature while utilizing Quasar's Q-Field validation

Currently, I am in the process of setting up a form using Quasar and implementing internal validation. The specific issue I am facing involves a group of checkboxes where the user must select at least one option. While I have successfully implemented the v ...

Exploring the Implementation of Box Icons in a Vuejs For Loop

I am currently exploring the box icons web component and I am trying to integrate the icons into my link array for each item. However, I am uncertain about the best approach to achieve this. <div class="container"> <div class="l ...

Interact with the exe/jar files on a remote machine using JavaScript

I've been tasked with finding a way to access an executable file (or any file located in a specific location like the C drive) directly from a web browser. The idea is to have a button on a webpage that, when clicked, will run the executable and pass ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

The issue arises when attempting to use the onChangeText function outside of the component and it fails to work

I am currently facing an issue with my test where the onChangeText function does not update the value of the TextInput component as expected. const TestComponent = ({onChangeText, value}) => { return (<TextInput testID={'input'} onChangeTex ...

Obtaining connection data in jsPlumb can be accomplished through a variety of

I have created a compact table of nodes that allow me to drag and drop connections or manually input node IDs to establish connections between them. Despite searching through the documentation and scouring the internet for examples, I am struggling to fin ...

Having trouble importing JSON into a variable in a React project

Recently, I started working with React and I'm facing a challenge regarding importing and saving selected JSON data into a variable [...] const languageToSet = "spanish"; const lang = { promiseToSetLanguage: function(lang){ retu ...

Showing a Div after a designated time of page loading: A simple guide

While I have a good understanding of CSS, Javascript is still new territory for me. I could use some guidance on the following task. My goal is to display a fixed div at the bottom of the screen, but I only want it to appear after a specific delay, say 10 ...

Tips for creating $http calls in AngularJS

Having some issues with my code, as I'm unsure of the correct placement for making an $http request to a local server. api.js var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); va ...

What is the best way to replace material-ui classNames with aphrodite styles?

Using React to style icons has been a fun experience for me. For the styling, I've relied on the incredible Material-UI library which offers a wide range of components. One such component is the FontIcon. However, I ran into an issue where the FontIc ...