I'm hoping someone can tell me why I'm failing to return a promise and call .then() on it.
I'm making an inventory system for my Pokemon cards with a react front-end and an express backend. When I hit the "increase inventory" button on the FE, here's 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...");
});
}
Here is the Express endpoint it's hitting:
// 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'm trying to return a promise from the endpoint. After the fetch on the FE, here is what the promise looks like before trying to call .then() on it:
But .then()
never runs. I don't even need the data from the fetch, really---i just need to trigger some code after the fetch is complete.
Hope someone can help me understand what I'm missing! Thanks!
You're returning the promise and resolving it, but you aren't sending any response back to the client with the res
.
In the express code, you don't need to have a promise, you can do 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);
}));
});