简体   繁体   English

可能未处理的 Promise 拒绝与 android 应用程序

[英]Possible Unhandled Promise Rejection with an android application

I've been practicing react native for the past few days.在过去的几天里,我一直在练习 react native。 And I'm trying to make a movie page application.我正在尝试制作电影页面应用程序。 My code works as it should be.我的代码可以正常工作。 But my problem is that it shows an error about a possible unhandled promise rejection.但我的问题是它显示了一个关于可能未处理的 promise 拒绝的错误。 I know where the problem is rooting from, but I don't know how to fix it.我知道问题出在哪里,但我不知道如何解决它。

Here is where the problem is rooting from (Details.js):这是问题的根源(Details.js):

import { isEmptyStatement } from '@babel/types';
import React, {useEffect, useState} from 'react';
import {Text} from 'react-native';
import {getMovie, getTv} from '../services/services';

const Detail = ({route, navigation}) => {
    const movieId = route.params.movieDetail.id;

    const [movieDetail, setMovieDetail] = useState([]);
    const [movieTv, setMovieTv] = useState([]);
    
    const [loaded, setLoaded] = useState(false);
    const [success, setSuccess] = useState(false);

    useEffect(() => {
        getMovie(movieId).then(movieData => {
            if(movieData == null) {
                setLoaded(false);
            }
            else {
                setMovieDetail(movieData);
                setLoaded(true);
            }
        });
    }, [movieId]);
    
    useEffect(() => {
        getTv(movieId).then(movieTv => {
            if(movieTv == null) {
                setLoaded(false);
            }
            else {
                setMovieTv(movieTv);
                setLoaded(true);
            }
        });
    }, [movieId]);

    if(movieDetail.title == null){
        return (
            <React.Fragment>
                {loaded && <Text>{movieTv.name}</Text>}
            </React.Fragment>
        );
    }
    else {
        return (
            <React.Fragment>
                {loaded && <Text>{movieDetail.title}</Text>}
            </React.Fragment>
        );
    }

    console.log(movieTv.success);
    
}

export default Detail;

And this is where they get the data (services.js):这是他们获取数据的地方(services.js):

import axios from 'axios';

const apiUrl = 'https://api.themoviedb.org/3';
const apiKey = 'api_key=31a7f8174b1e2c29744ec644af796973';

// Get Popular Movies
export const getPopularMovies = async () => {
    const resp = await axios.get(`${apiUrl}/movie/popular?${apiKey}`,);
    return resp.data.results;
};

// Get Upcoming Movies
export const getUpcomingMovies = async () => {
    const resp = await axios.get(`${apiUrl}/movie/upcoming?${apiKey}`,);
    return resp.data.results;
};

// Get Popular TV
export const getPopularTv = async () => {
    const resp = await axios.get(`${apiUrl}/tv/popular?${apiKey}`,);
    return resp.data.results;
};

export const getFamilyMovies = async () => {
    const resp = await axios.get(`${apiUrl}/discover/movie?${apiKey}&with_genres=10751`,);
    return resp.data.results;
};

export const getMovie = async id => {
    const resp = await axios.get(`${apiUrl}/movie/${id}?${apiKey}`,);
    return resp.data;
};

export const getTv = async id => {
    const resp = await axios.get(`${apiUrl}/tv/${id}?${apiKey}`,);
    return resp.data;
};

You have used several async calls and working on the returned promises in your Details.js class.您已经使用了多个异步调用并在您的Details.js class 中处理返回的承诺。 But in each such case, you have only handled the success (promise resolve) path by providing only the then callback.但在每种情况下,您只通过提供then回调来处理成功(承诺解决)路径。

For example, consider this例如,考虑这个

getTv(movieId).then(movieTv => {
    if(movieTv == null) {
        setLoaded(false);
    }
    else {
        setMovieTv(movieTv);
        setLoaded(true);
    }
});

Here your application will work well, as long as the network call is successful and the backend returns a successful (eg 2xx) response .只要网络调用成功并且后端返回成功(例如2xx)响应,您的应用程序将运行良好。 But if any error occurred, your application will crash as you haven't handled the error by handling the promise rejection.但是如果发生任何错误,您的应用程序将崩溃,因为您没有通过处理 promise 拒绝来处理错误。

So what you should do is add a catch callback to each of these promises and handles the error scenario gracefully.所以你应该做的是为每个 Promise 添加一个catch回调并优雅地处理错误场景。 You can do things like logging the error, set any flag to indicate the loading was failed, show an error on the UI etc.您可以执行诸如记录错误、设置任何标志以指示加载失败、在 UI 上显示错误等操作。

getTv(movieId).then(movieTv => {
    if(movieTv == null) {
        setLoaded(false);
    }
    else {
        setMovieTv(movieTv);
        setLoaded(true);
    }
}).catch(err => {
  console.log(err);
  setLoaded(false);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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