Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return resolved promise value

  const displayCharacters =  async () => { 
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };

      const b = await fetch("/image",options).then(res => res.json())
      return b; 

    }else{
      return "yikes";
    }
  }


  console.log(displayCharacters());

I have this fetch request but when I log the results this is what i see :

Promise {<resolved>: "yikes"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "yikes"

I just want the promiseValue and not this whole thing around it. How do i do this?

like image 383
Kevin.a Avatar asked Apr 12 '26 22:04

Kevin.a


1 Answers

the async function returns a promise instantly, without waiting for the promise to resolve. You may instead console.log inside the function:

  const displayCharacters =  async () => { 
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };
      try {
        const b = await fetch("/image",options).then(res => res.json());
        console.log(b);

        //the better practice is however, to do like:
        const b = await fetch("/image",options)
        const result = await b.json(); 
        console.log(result );
      }
      catch(err) {
         console.log(err);
      }

    }else{
      console.log("yikes");
    }
  }


displayCharacters();
like image 113
Addis Avatar answered Apr 14 '26 12:04

Addis