【问题标题】:Is it a right syntax for async request using fetch api?使用 fetch api 进行异步请求的语法是否正确?
【发布时间】:2019-01-14 18:52:25
【问题描述】:

我正在使用 Fetch API 发出多个发布请求。但是当我运行此代码时,任何一个请求都会失败。两个请求都可以单独正常工作。下面是代码。这是使用 Fetch API 发出多个帖子请求的正确方法吗?

let req1 = fetch("http://localhost/hplus/statelist", {
method : "post",
headers : {
    "Accept" : "application/json",
    "Content-type" : "application/x-www-form-urlencoded"
},
body : ""
}).then(res => res.json());

let req2 = fetch("http://localhost/hplus/citylist", {
method : "post",
headers : {
    "Accept" : "application/json",
    "Content-type" : "application/x-www-form-urlencoded"
},
body : "stateid=1"
}).then(res => res.json());

Promise.all([req1, req2]).then(val => console.log(val));

【问题讨论】:

  • “失败”是什么意思?你得到什么错误?
  • 什么是localhost/hplus/citylist,它运行的是什么服务器?它是否正确处理并发请求?
  • 失败意味着无法将数据发布到服务器并返回未定义的索引@Bergi
  • localhost/hplus/citylist 是本地服务器 URL。应用程序正在 XAMPP 服务器上运行
  • 代码对我来说看起来不错。您是否有权访问服务器的代码或日志?检查它是否收到了两个请求,以及它如何响应每个请求。您的服务器可能在短时间内遇到两个请求的问题,您希望在服务器端解决。

标签: javascript fetch-api


【解决方案1】:
let req1 = fetch("http://localhost/hplus/statelist", {
method : "post",
headers : {
    "Accept" : "application/json",
    "Content-type" : "application/x-www-form-urlencoded"
},
data : ""
})

这部分已经返回了一个承诺。

当您附加 .then() 部分时,将返回已解决的承诺的结果。所以,fetch(something).then(something) 不是一个承诺。

Promise.all([A list of promises]) 需要只有 promise 部分。

这是你需要做的事情。

let req1 = fetch("http://localhost/hplus/statelist", {
method : "post",
headers : {
    "Accept" : "application/json",
    "Content-type" : "application/x-www-form-urlencoded"
},
data : ""
});

let req2 = fetch("http://localhost/hplus/citylist", {
method : "post",
headers : {
    "Accept" : "application/json",
    "Content-type" : "application/x-www-form-urlencoded"
},
body : "stateid=1"
});

Promise.all([req1, req2]).then(val => console.log(val));

【讨论】:

  • 但我需要一个结果部分而不是一个承诺
  • Promise.all([req1, req2]).then(val => console.log(val)); val 是这里的结果,其中 val[0] 的结果是 req1,val[1] 的结果是 req2
  • 我想指出这个解释是不正确的。 When you append the .then() part, the result of the resolved promise is returned. So, fetch(something).then(something) is not a promise. 这是不正确的:当您将.then.catch 等链接到一个promise 时,结果是一个新的Promise。您在处理程序中返回的任何内容都会自动包装在一个新的 Promise 中,如果它还不是一个(但是,res.json() 无论如何已经是一个)。
猜你喜欢
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
  • 2018-02-11
  • 2022-01-10
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多