React Native 中可能存在未处理的 Promise 拒绝(id:0)

问题描述 投票:0回答:1

当我声明

async
函数两次时,会发生此错误:

React Native 中可能存在未处理的 Promise 拒绝(id:0)

类别.jsx

import { View, Text } from "react-native";
import Heading from "../../Component/Heading";
import GlobalApi from "../../Utils/GlobalApi";
import React, { useEffect } from "react";

export default function Categories() {
  useEffect(() => {
    getCategories();
  }, []);

  const getCategories = () => {
    GlobalApi.getCategories()
      .then((resp) => {
        console.log("resp", resp.categories);
      });
  };

  return (
    <View>
      <Heading text={"Categories"} isViewAll={true} />
    </View>
  );
}

API类

import { request, gql } from "graphql-request";

const MASTER_URL =
  "https://api-ap-south-1.hygraph.com/v2/clrud3zbv0zjm01w12p1qw5x8/master";

const getSlider = async () => {
  const query = gql`
    query GetSlider {
      sliders {
        id
        name
        image {
          url
        }
      }
    }
  `;
  const result = await request(MASTER_URL, query);
  return result;
};

const getCategories = async () => {
  const query = gql`
    query GetCategory {
      categories {
        id
        name
        icon {
          url
        }
      }
  `;
  const result = await request(MASTER_URL, query);
  return result;
};

export default {
  getSlider,
  getCategories,
};

我尝试了一切,但无法解决这个问题。我尝试创建新类并调用 API,但仍然收到该错误或警告。

javascript react-native async-await
1个回答
0
投票

getSlider
getCategories
函数都返回一个 Promise 对象,除了活动的挂起状态之外,Promise 只能解决或拒绝。您的代码只需要添加处理被拒绝的 Promise 或 Promise 链执行期间是否抛出任何异常。 const getCategories = () => { GlobalApi.getCategories() .then((resp) => { console.log("resp", resp.categories); }) .catch(error => { // catch and handle/ignore/etc any rejected Promise or thrown error }); };

或用 
async/await

 转换为 
try/catch
const getCategories = async () => {
  try {
    const resp = await GlobalApi.getCategories();
    console.log("resp", resp.categories);
  } catch(error) {
    // catch and handle/ignore/etc any rejected Promise or thrown error
  };
};

© www.soinside.com 2019 - 2024. All rights reserved.