0

I can get the data easily from PromiseValue if I use it without await but since I'm using await to make the request Synchronous I can't get the data out of the function

currently I'm getting the data like this

Promise {pending}

proto: Promise

[[PromiseStatus]]: "resolved"

[[PromiseValue]]: ... html data goes here!

there's no way I can get the data from PromiseValue out of function I can only print them.

how can I get PromiseValue data while using Synchronous await method

the code I have now

 const request =   (async () => {

        const response = await   fetch(url,
        {
            method: 'get',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });

       const data =  await    response.text();

       console.log(data);

    })();
    return  request;

I can print out the data but I can't get them out of the function

  • 1
    an async function returns a promise. if you are running this in the scope of another function that is also asynchronous, just add in an await in front of the outermost async function, i.e. `const request = await (async...` – Jhecht Jan 21 '20 at 03:58

1 Answers1

2

simply pass the data variable to a new function that is defined outside of your async function.

For example

const request = (async () => {

    const response = await fetch("https://docs.google.com/document/d/1Wv-nOpEoHaGsNhCFeuQHn-5vVnrDCp0jp8_VuK-RZ68/export?format=txt",
        {
            method: 'get',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });

    const data = await response.text();
    hiThere(data);
})();

function hiThere(d) {
    console.log(d)
}
ankitkanojia
  • 3,072
  • 4
  • 22
  • 35