[英]I have a fetch request for HTML data and returns a Promise
我向 php 页面发出请求,我只使用 get 传递变量并在页面上处理它们,数据正在正确处理,我确实得到了我想要的结果,但是下面显示了我 go 通过从控制台日志
async function postData() {
const response = await fetch(
'multi-test.php?search='+ name.data,
{
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "same-origin", // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "text/plain" // sent request
},
referrerPolicy: 'no-referrer',
},
)
.then((serverPromise) => console.log(serverPromise.text()));
return response;
}
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Data I want
这个获取经历了几个阶段,从挂起到完成我如何只在 [[PromiseState]]: "fulfilled" 时获取数据,另外我如何获得 [[PromiseResult]]
async function postData() {
const response = await fetch(
'multi-test.php?search='+ name.data,
{
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "same-origin", // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "text/plain" // sent request
},
referrerPolicy: 'no-referrer',
}
)
const result = await response.json();
return result;
}
https://developer.mozilla.org/en-US/docs/Web/API/Response可能会有所帮助
由于您使用的是异步 function。 您可以在 response.data 中访问您的数据
如果您正在使用 await 功能,则不需要将 fetch 方法与.then 链接。 一旦 promise 完成。 您的数据将存储在响应 object 的数据属性中。
您还可以尝试在获取数据时立即解构数据。
async function postData() {
const {data} = await fetch("multi-test.php?search=" + name.data, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "same-origin", // no-cors, *cors, same-origin
cache: "no-cache",
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "text/plain", // sent request
},
referrerPolicy: "no-referrer",
})
return data;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.