【发布时间】:2021-02-12 13:27:14
【问题描述】:
我希望有人能告诉我为什么我没有返回一个承诺并调用 .then() 。
我正在为我的 Pokemon 卡片创建一个库存系统,其中包含一个 react 前端和一个 express 后端。当我点击 FE 上的“增加库存”按钮时,调用 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...");
});
}
这是它命中的 Express 端点:
// 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);
}));
});
如您所见,我正在尝试从端点返回一个承诺。在 FE 上 fetch 之后,这是在尝试调用 .then() 之前 promise 的样子:
但是.then() 永远不会运行。我什至不需要 fetch 中的数据,真的——我只需要在 fetch 完成后触发一些代码。
希望有人可以帮助我了解我所缺少的!谢谢!
【问题讨论】:
-
您是否也尝试过
.catch来检查错误? -
您是否尝试过在服务器中使用
res.send()进行实际响应? - 服务器代码中返回的 Promise 不是您对请求发送响应的方式 - 查看如何使用 express - expressjs.com/en/starter/hello-world.html -
@JaromandaX 不像这个问题中的口袋妖怪,OP 似乎不想抓住他们所有
-
@Phil - 我的天啊!!!你是爸爸对吧!!! :p
-
你们完全是我的星期五
标签: javascript express mongoose promise fetch