Home > Mobile >  I have a fetch request for HTML data and returns a Promise
I have a fetch request for HTML data and returns a Promise

Time:09-26

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]]

CodePudding user response:

  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

CodePudding user response:

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