Home > Enterprise >  Confused by async behavior
Confused by async behavior

Time:03-29

I'm using a try/catch to make some fetch requests, then I am extracting the title from the HTML and adding it to my object 'sleekResponse' When I try to parse the body and add it to that object I'm having issues with the return value not including the title that I extracted from the HTML

I know this has something to do with asynchronicity, or my shallow understanding of Promises, but I can't tell why the return value is different from the value it's logging just before it's sent.

async function fetchUrl(url) {
  console.log(url);
  try {
    const myInit = {
      mode: 'cors'
    }

    let sleekResponse = {};

    await fetch(url, myInit).then(function (response) {
      sleekResponse.redirected = response.redirected;
      sleekResponse.status = response.status;
      return response;
    })
    .then((response) => titleWait(response))
    .then((res) => sleekResponse.title = res)

    function titleWait(response) {
      Promise.resolve(response.text()).then((res) => {
        a = res.split('<title>');
        b = a[1].split('</title>')
        sleekResponse.title = b[0];
        return sleekResponse;
      })
      console.log(sleekResponse);
      return sleekResponse;
    }

    console.log(sleekResponse); // This logs the correct value
    return sleekResponse; // when it's returned it doesn't show the title that was added
  } catch (err) {
    return `${err}`;
  }
}

I've tried so many things I don't remember everything that I tried. I know that I'm missing something that might be obvious, but I still don't understand why the console.log value is different from the value returned one line later.

CodePudding user response:

The main issue is that titleWait doesn't return its own promise:

    function titleWait(response) {
      return Promise.resolve(response.text()).then((res) => {
        a = res.split('<title>');
        b = a[1].split('</title>')
        sleekResponse.title = b[0];
        return sleekResponse;
      })
      console.log(sleekResponse);
      return sleekResponse;
    }

It's still a very convoluted way to write it. This is better:

    async function titleWait(response) {
      const res = await response.text());
      const a = res.split('<title>');
      const b = a[1].split('</title>')
      sleekResponse.title = b[0];
      return sleekResponse;
    }

CodePudding user response:

i hope i can a litel help

this basic fetch();

const response = await fetch('your url') 

const data = await response.json();

console.log(data);

  • Related