【发布时间】:2022-03-15 17:49:27
【问题描述】:
**edit: 后端有问题
所以我一直遇到链接承诺的问题。我放弃了 axios 并 async await 回去重新学习基础知识,因为我一定在某个地方犯了一个简单的错误,但我没有运气。希望有人可以看看吗?
我按以下顺序调用以下路由:
/users/register/users/all/delete/:id/users/all
问题是代码应该添加一个用户,然后删除同一个用户,但我会说每 6 个左右调用 1 个,第 2 步和第 4 步(显示所有用户)都显示新添加的用户- 这是不正确的。
但据我所知,我正确地将承诺和调用链接在一起。
我一定遗漏了一些明显的东西,但我真的看不到它。如果我错在哪里,我会很感激第二双眼睛或方向
function test() {
fetch(`http://localhost:8080/users/register`, { **//1**
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ firstName: 'nick', lastName: 'smith', phone: '01980635243', email: 'nick@hotmail.com', password: '1234567891011', confirmPassword:'1234567891011'})
})
.then(res => res.json())
.then(res => {
console.log(res);
return fetch('http://localhost:8080/users/all') **//2**
})
.then(res => res.json())
.then(res => {
console.log(res)
return fetch('http://localhost:8080/users/delete-email/nick@hotmail.com', { **//3**
method: 'DELETE',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
}
});
})
.then(res => res.json())
.then(res => {
console.log(res)
return fetch('http://localhost:8080/users/all'); **//4**
})
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err));
}
【问题讨论】:
-
它们的链接很好,但是你想保留所有的结果吗?最好不要将它们链接起来并在一个数组和 Promise.all 中将它们全部关闭?
-
你确定这与 fetch/promises 有什么关系吗?如果最终执行了所有操作,那么服务器对您的 GET 的响应很可能与您预期的不一致。
-
不完全不,也许它可能在服务器端,但每次我测试单个路由时它似乎都有效。我想至少如果我知道上面的代码是正确的,我可以开始关注它。
-
@evolutionxbox 你不能并行运行这些。它们必须按顺序运行,因为每个 Promise 都取决于前一个操作的结果..
-
我只是看不到第 4 步如何返回相同数量的数组值 - 我从服务器得到正确的响应,我可以看到它正在被删除 - 所以它肯定有成为一个承诺问题?以上是除了调用
test()之外的唯一代码。
标签: javascript promise fetch-api