Issue with Promise failing to trigger .then() following fetch to Express API/Mongoose request

Can someone shed light on why I am unable to return a promise and invoke .then() on it?

I am creating an inventory system for my collection of Pokemon cards using a react front-end and an express backend. When I click the "increase inventory" button on the front end, this is the function that calls the API:

incInventory(card, cond) {
  // this.setState({currentValue: this.state.currentValue + 1});
  const result = fetch('http://mySecretAPIServer/items/' + card._id, {
    method: 'PUT',
    headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    },
    // We convert the React state to JSON and send it as the POST body
    body: JSON.stringify({_id: card._id, cond: cond, op: "incQuantity", otherId: card.id})
  });
  console.log(result);
  // ***WHY ISN'T THIS RUNNING?!?!?!?***
  result.then((res) => {
    console.log("this isn't printing...");
  });
}

This is the Express endpoint being accessed:

// UPDATE (Modify)
router.put('/:id', (req, res) => {
    const conditionToUpdate = "q" + req.body.cond;
    const amtToUpdate = req.body.op === 'incQuantity' ? 1 : -1;

    return new Promise((resolve, reject) => 
        Pokemon.findByIdAndUpdate(req.params.id, {$inc: {[conditionToUpdate]: amtToUpdate}}, (err, result) => {
            resolve(result);
        }));
});

As you can see, I am attempting to return a promise from the endpoint. After the fetch call on the front end, here is what the promise looks like before trying to use .then() on it:

https://i.sstatic.net/HvsOQ.png

However, the .then() function never executes. I don't necessarily need the data from the fetch, I just need to execute some code after the fetch completes.

I hope someone can guide me in figuring out what I may be overlooking! Thank you!

Answer №1

It's important to note that while you are resolving the promise, you must also send a response back to the client using the res object.

In your express code, there is no need to use a promise. You can simplify it like this:

router.put('/:id', (req, res) => {
    const conditionToUpdate = "q" + req.body.cond;
    const amtToUpdate = req.body.op === 'incQuantity' ? 1 : -1;

    Pokemon.findByIdAndUpdate(req.params.id, {$inc: {[conditionToUpdate]: amtToUpdate}}, (err, result) => {
        res.json(result);
    }));
});

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

When working with Firebase, I am required to extract data from two different tables simultaneously

When working with Firebase, I have the need to extract data from tables/nodes. Specifically, I am dealing with two tables - one called jobs and the other called organisations. The outcome I am looking for: I want to retrieve all companies that do not hav ...

"Eliminate any inline styling from a string element with the power of JavaScript/j

If I have the following string: let sentence = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>'; This string contains multiple elements a ...

Error: Provider not recognized

Currently, I am in the process of creating a basic chat application using express.js, socket.io, and angular. The functionality seems to be working properly. However, I am encountering an issue where the socket message event is not synchronizing and displa ...

Fill the second dropdown menu options based on the selection made in the first dropdown menu

I need assistance with dynamically populating my second drop-down menu based on the selection made in the first drop-down. Here are the steps I've taken so far: form.php - Utilizing javascript, I have set up a function to call getgeneral.php. The se ...

Matching Javascript Variables to CSS Styles

I am currently developing a small HTML page and I am utilizing JavaScript to retrieve the screen dimensions. However, I am facing an issue with passing this variable to a CSS style as shown below. How can I achieve this successfully? Additionally, I have ...

Unable to execute xmlHttp.responseXML on a server that is offline

Currently, I am diving into the world of AJAX and XML. However, I recently encountered a frustrating issue. I attempted to create a basic program that would display everything I input into an input box within a <div>. Strangely enough, my program fa ...

Connect to the MongoDB database running on localhost using the mongoose library

I am currently learning about the MEAN stack through this helpful tutorial. However, the tutorial assumes a connection to a remote mongodb installation. I have MongoDB already set up and running on my CentOS7 localhost. To modify the mongoose connect line ...

Leverage es6 classes along with mongoose in typescript to utilize loadClass functionality

I've been struggling with a problem and despite my exhaustive search on Google, I still haven't found a solution. My issue revolves around incorporating es6 classes with mongoose using the schema.loadClass(class) method. Unfortunately, when worki ...

At what point is the ajax call considered fully executed?

Whenever a client makes an AJAX call, they upload data to the server (HTTP request) and then receive data from the server (HTTP Response). Once the clients have received all the data, the AJAX request is considered successful, and the success callback func ...

Transferring JSON information to the database via Postman results in an error code 500

I encountered an internal server error while trying to send JSON data using Postman. I have ensured that the connections and schemas are properly established, but I am unable to pinpoint the source of this error. CODE const asyncHandler = require("exp ...

The function addEventListener is not found

When a button is pressed, I want to add a value into a container by adding an event listener. <div className="grid-container"> <div> <button id="redBet" className="redButton" onclick={thi ...

Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component. When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. Thi ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

What is the process for linking a SQL server to the app.js file?

I currently have a directory named NEsql, which is located within another folder named sqlnames1. Inside the NEsql folder are the following individual files. sqlcreatedb.js var mysql = require('mysql'); var con = mysql.createConnection({ hos ...

The value of req.body.stripeToken is not defined

I am facing an issue while using $http to post a form to my nodejs server. Upon posting, I attempt to retrieve the variable stripeToken using req.body.stripeToken in my server code, but it always returns undefined. Interestingly, when I make the post requ ...

AngularJs throw an error when trying to use $q which is not defined on the console

Encountering an error message in the console stating $q is not defined. After doing some investigation, it appears that the .q library has been deprecated as mentioned on If this information is accurate, then it implies that the entire concept of promises ...

Exploring cookie management in AngularJS using the $http service

Currently, I am facing a challenge in implementing authentication using ExpressJS' cookie sessions and AngularJS. The issue I am encountering is that even though I have managed to get ExpressJS to send session cookies, Angular does not send them with ...

ASP updatepanel textbox focusing - Working only with breakpoints, not without them

I've encountered a bizarre problem where my code functions perfectly with a breakpoint set, but when I remove the breakpoint, certain parts of the code fail to work. My goal is to have a textbox automatically select all text upon focus; it should foc ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...