Kevin.a
Kevin.a

Reputation: 4296

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?

Upvotes: 3

Views: 83

Answers (2)

thinparfiet
thinparfiet

Reputation: 108

The best way that i know to use fetch goes something like this:

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 => {
        // Handle API Errors
        if (!res.ok) {
          throw Error(res.statusText);
        }
        // Return if no errors
        return res.json();
      })
      // this is the data you want
      .then(data => data)
      // it will only reject on network failure or if anything prevented the request from completing
      .catch(error => {
        console.log(error.message)
      });

    return b; 

  }else{
    return "yikes";
  }
}

Basically you chain two thens and a catch to completely understand the response - the first then checks for api level errors - second then gets you the data - catch is invoked in case when it is not able to reach the api itself like connection issues

Upvotes: 0

Addis
Addis

Reputation: 2530

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();

Upvotes: 2

Related Questions