在 promise fetch 调用后反应 Class 如何 return 一个布尔值

React Class how to return a Boolean after a promise fetch call

你好我有这个 class 当我从另一个组件调用 Auth.isAuthenticated() 时,它总是 return false(它的默认值),即使服务器 return 200 响应, 设置 this.authenticated = true 。 我如何使用 promises 让方法等到 fetch 调用完成然后 return 结果

编辑: 我需要布尔值 true 或 false returned 所以基于此,我可以显示或隐藏组件,所有答案都有帮助但我需要一个布尔值而不是承诺任何帮助

    class Auth {
    constructor() {
        this.authenticated = false;
    }


    isAuthenticated() {
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        }).then(
            (response) => {
                response.json()
                    .then((res) => {
                        if (response.status === 200) {
                            this.authenticated = true;
                        }
                        if (response.status === 401) {
                            localStorage.removeItem('jwttoken');
                            this.authenticated = false;
                        }
                    })
            }
        ).catch((err) => {
            // console.log(err)
        });

        return this.authenticated;
    }


}



export default new Auth();

我从另一个组件调用 Auth.isAuthenticated() === true

export const PrivateRoute = ({ component: Component, ...rest }) => {

  return (
    <Route {...rest} render={(props) => (
      Auth.isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/admin' />
    )} />
      )
}

使用异步等待

async isAuthenticated() {
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        const response = await fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        });

        const responseToJson = await response.json();

         if (responseToJson.status === 200) {
             this.authenticated = true;
         }
         if (responseToJson.status === 401) {
             localStorage.removeItem('jwttoken');
             this.authenticated = false;
         }

       return this.authenticated;
    }

如果你不想做 async/await 你可以 isAuthenticated return 一个承诺。

isAuthenticated() {
  return new Promise((resolve, reject) => {
    //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        }).then(
            (response) => {
                response.json()
                    .then((res) => {
                        if (response.status === 200) {
                            resolve(true)
                        }
                        if (response.status === 401) {
                            localStorage.removeItem('jwttoken');
                            resolve(false)
                        }
                    })
            }
        ).catch((err) => {
            // reject(err)
        });
  })        
}

在异步函数内你可以做let isAuthenticated = await isAuthenticated()或者你可以在异步函数外使用.then.catch到return结果

假设您想编写一个 returns 承诺并在某些操作完成时解析的函数(例如 API 调用)。你可以这样写:

const myAsyncFunction = () =>{
    return new Promise((resolve, reject) =>{
        //Faking an API Call
        setTimeout(() => resolve('data'), 400)
    })
}

给你!现在你有一个 returns 将在 400 毫秒内解决的承诺的功能。现在您需要使用 .then() 方法或 async await 语句。

const sideEffects = async () =>{
    const result = await myAsyncFunction()
    console.log(result) //'data'
}