简体   繁体   中英

React Native get return value of async function

I am trying to get pub locations data from MYSQL server and my fetch function works well. But after that, this try-catch block does not return anything. I also tried without try-catch block but it does not change anything

  getPubsFromDatabase = async () => {
    let response = await fetch(fetchDataUrl, {
      method: 'POST',
      headers: 
      {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
    });
    try{
      let json = await response.json();
      console.log(json)
      return json;
    }
    catch (error) {
      console.log(error);
    }
  }

And here, I am trying to get the return value of the function. But in this version, I cannot even see any console.log output. What I mean by the version is, if I put 2nd line out of the async block without "await" keyword, I can see the console.log but I it gives "undefined" then.

  (async () => {
    const locationsData = await getPubsFromDatabase();
    console.log(locationsData)
  })()

You can use then and catch in the function fetch .

  const getPubsFromDatabase = () => {
    return fetch(fetchDataUrl, {
      method: 'POST',
      headers: 
      {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
    }).then(async (response) => {
      const json = await response.json().then((data)=>{
        return data;
      }).catch((err)=>{
        console.log('error from json method: ',err);
        return  { error: {
         message: 'error from json method',
         object: err
        }};
      });
      console.log(json);
      return json;
    }).catch((error) => {
      console.log('error from request: ', error);
      return  {
        error: {
          message: 'error from request', object: error
        }
      };
    });
  }

And when you use the method getPubsFromDatabase would be of the next way:

  (async () => {
    const locationsData = await getPubsFromDatabase();
    console.log(locationsData);
  })()

You can use Promise to return either result or error, In the example given below i have used axios library but you can also try same with fetch api For Example

export const getData = () => {

  return new Promise((resolve, reject) => {
    const url = ApiConstant.BASE_URL + ApiConstant.ENDPOINT;
    const API_HEADER = {
      "Authorization": token,
    };

    axios
      .get(url, {
        headers: API_HEADER,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        // handle error
        reject(error);
        console.log(error);
      });
  })
}

You can call the above function in component or screen like this:

getData().then(
            (data: any) => {

            }
        ).catch(
            error => {
                console.log(error)
            }
        )

I solved the problem by instead of returning the value from the function, I set the value inside the function. This seems to work now.

  const [locationsData, setLocationsData] = useState();
  getPubsFromDatabase = async () => {
    let response = await fetch(fetchDataUrl, {
      method: 'POST',
      headers: 
      {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
    });
    try{
      let json = await response.json();
      setLocationsData(json); // Here, I changed the value of the locationsData instead of returning
    }
    catch (error) {
      console.log(error);
    }
  }

And to call the function:

  useEffect(()=> {
    getPubsFromDatabase();
  },[])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM