简体   繁体   中英

I have a fetch request for HTML data and returns a Promise

I make a request to a php page where I just use a get to pass in variables and process them on the page the data is being processed correctly and I do get the result I want however below shows the process of results I go through from a console.log


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

This fetch goes through stages and goes from pending to fulfilled how do I only get the data when the [[PromiseState]]: "fulfilled" and additionally how do I get [[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 may help

Since you are using async function. You can access your data in response.data

You do not need to chain the fetch method with.then if you are using await functionality. Once the promise is fulfilled. You data will be stored in the data property of response object.

You can also try destructuring the data right away when fetching the data.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM