javascript - React 类如何在 promise 获取调用后返回 bool 值

标签 javascript reactjs es6-promise

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

编辑: 我需要返回 bool 值 true 或 false,因此基于此,我可以显示或隐藏组件,所有答案都有帮助,但我需要一个 bool 值而不是 promise 任何帮助请

    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' />
    )} />
      )
}

最佳答案

假设您要编写一个函数,该函数返回一个 promise 并在某些操作完成时解析(例如 API 调用)。你可以这样写:

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

给你!现在你有一个函数返回一个将在 400 毫秒内解决的 promise 。现在您需要使用 .then() 方法或 async await 语句。

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

关于javascript - React 类如何在 promise 获取调用后返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405187/

相关文章:

javascript - Node 请求 - 想要在完成后返回路径/文件名吗?或者任何最佳实践建议

javascript - 使用 AJAX 的数据表 - 如何与特定页面共享 URL?

javascript - 有哪些依赖于 'typeof null' 返回对象的代码示例?

javascript - 是否可以在created()完成后运行v-for?

reactjs - 如何使用express为react-router应用程序路由?

javascript - 组件无法识别它正在导出

javascript - AWS Lambda 返回而不等待 promise

javascript - 在目录中查找文件

javascript - 如何从 jQuery .click() 内部调用方法并保持上下文?

javascript - 在胜利图表方面需要一些帮助