Leveraging async-await for carrying out a task following the deletion of a collection from a mongodb database

Trying to implement async await for executing an http request prior to running other code. Specifically, wanting to delete a collection in the mongodb database before proceeding with additional tasks. This is what has been attempted:

app.component.ts:

  async deleteRiskRatingData2() {
      await this.saveInformationService
      .deleteRiskRatingInformation()
      .subscribe((data: string) => {
        console.log('Deleting risk Rating');
        console.log(this.riskRatingTable);
      });
      console.log('TASKS TO BE EXECUTED AFTER DROPPING COLLECTION');
  }

save-information.service.ts

  deleteRiskRatingInformation() {
    console.log('INIDE deleteRiskRatingInformation INSIDE SAVE-INFORMATION.SERVICE');
    return this.http.get(`${this.uri}/dropRiskRatingCollection`);
  }

On the server side:

server.js

router.route('/dropRiskRatingCollection').get((req, res) => {
    RiskRating.remove({},(err) => {
        if (err)
            console.log(err);
        else
            res.json("Risk Rating Collection has been dropped!");
    });
});

The result:
https://i.stack.imgur.com/ONv6d.png

Expected Async/Await implementation to execute:

  console.log('TASKS TO BE EXECUTED AFTER DROPPING COLLECTION');

This did not occur as intended. Confusion surrounds why this is happening. Is there a flaw in the logic? And how can the goal be accomplished?
Thank you!

Answer №1

async-await are designed to work specifically with Promises. If you attempt to use them with Observables, it will not yield the desired results. However, Observables have an API that allows you to convert them into Promises by using the toPromise method.

Here is an example:

async deleteRiskRatingData2() {
  const data = await this.saveInformationService.deleteRiskRatingInformation().toPromise();
  console.log('Deleting risk Rating');
  console.log(this.riskRatingTable);
  console.log('TASKS TO BE EXECUTED AFTER DROPPING COLLECTION');
}

NOTE: While it may be tempting to switch back to promises just to utilize async-await for a more synchronous code flow during testing, it is not recommended in practice.

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

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

Having trouble with eslint in create-react-app because of a parent folder that also has another app with its own node_modules folder?

I have a git repository with two projects inside: a loopback app (named app) and a create-react-app react app (named client). Here is the directory structure: ├─┬app │ ├──node_modules │ ├─┬client ├─node_modules The loopback ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

Create a recursive CSS style for an angular template and its container

I am struggling with styling CSS inside an ng-container that is used in a tree recursive call to display a tree hierarchy. <ul> <ng-template #recursiveList let-list> <li *ngFor="let item of list" [selected]="isSelected"> <sp ...

Turn off the authentication middleware for a particular HTTP method on a specific endpoint

Currently, I am using Express/Node and have developed authentication middleware to validate JWT on each request. My requirement is to disable this middleware for a specific route (POST '/api/user/') while keeping it active for another route (GET ...

Guide to navigating to a different webpage with Node.js

I am a beginner user of NodeJS and I have a specific request. I need assistance with setting up a page redirect from one page to another upon clicking on a link. Any guidance provided will be greatly appreciated. Here is the code snippet: app.js var expr ...

An error occurred while trying to update with Webpack Dev Server: [HMR] Update failed due to an issue fetching the update manifest,

I encountered an issue in the browser console while attempting to live reload / HMR on Webpack. The error arises after saving a file following a change. [HMR] Update failed: Error: Failed to fetch update manifest Internal Server Error Could the failure b ...

Encountering difficulties during the installation of tensorflow.js using npm

I attempted to install the necessary package using the command provided in the tensorflow documentation: npm install -g @tensorflow/tfjs-node Despite my best efforts, I have been unable to identify a solution to the problem. Any assistance in resolving th ...

Publishing on Npm necessitated my presence being logged in despite the fact that I was already logged in

I've been encountering some issues with deploying my npm package. Initially, I deployed it manually by running 'npm publish' and everything went smoothly, with the package being successfully published. However, I wanted the package to be aut ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

The Google Drive API in Node.js is notifying the deletion of files

I encountered an issue with the Google Drive API in my application. Even after deleting files from Google Drive, the listfiles function still returns those deleted files. Is there a solution to prevent this from happening? Below is the function of my API: ...

boost the amount of responses received per second

I have developed an android game with a user base of 40,000 online users. Each user is sending a request to the server every 5 seconds. Below is the code I have written to test these requests: const express = require('express') const app = ex ...

Transferring a substantial file to a NodeJS server for storage

Currently, I am utilizing a NodeJS server (ExpressJS) to host my web application. A new requirement has surfaced which involves allowing users to upload large videos (potentially gigabytes in size) to the server, with the ability for them to later download ...

encountered an error stating module '@angular/compiler-cli/ngc' could not be located while attempting to execute ng serve

Here is the content of my package.json file: { "name": "cal-euc", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build&qu ...

Trouble with the 'uppercase' package in Node.js: Receiving ERR_REQUIRE_ESM error while utilizing the require() function

I am encountering a problem with the 'upper-case' module while developing my Node.js application. My intention is to utilize the upper-case module to convert a string to uppercase, but I'm running into difficulties involving ESM and require( ...

What is the process for importing a server app in Chai for making requests?

I am looking to conduct tests on my node express server, but the way this application starts the server is as follows: createServer() .then(server => { server.listen(PORT); Log.info(`Server started on http://localhost:${PORT}`); }) .catch(err =& ...

Having trouble querying and printing all records from MongoDB using a Python script

I am storing student records such as student_name and student_grade in mongodb. Once I insert records, I attempt to display all the records. student_name, student_grade = raw_input("Enter student name & grade:").split(',') # Assigning value ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

Tips for configuring the node_modules/lib path in an AngularJS project

I have been trying to see if the image is working properly. Is there a way to utilize global libraries for node_module? The installation seems to be in the correct place - c:\user\AppData\Roaming\npm\node_modules However, I a ...

Adding personalized modules in Node Express

I'm a beginner in the world of Node.js and Express, and I am a bit confused about where to place certain files... I have some custom code that I want to use in my Express application - where should I store this code? Currently, it seems like I need t ...