如何按常规顺序使用异步等待?

时间:2021-04-09 13:42:12

标签: javascript node.js reactjs react-native

当我采取行动时,按 onPress={() => Login()} 函数

首先,我想通过使用 signInWithKakao 函数来获取令牌, 其次,在我获得令牌之后,如果我有令牌,我想通过使用发送配置文件 kakaoprofile函数

如果我在按下按钮时使用我的代码,就会发生这个错误

  token is not defined 

我认为是因为 signInWithKakao 无法识别,因为它在登录功能中。

如何修复我的代码?

这是我的代码

import {
  getProfile as getKakaoProfile,
  login,
} from '@react-native-seoul/kakao-login';

const Kakao = () => {

  const [result, setResult] = useState('');

  const Login = () => {

    const signInWithKakao = async() => {
      const token = await login();
      setResult(JSON.stringify(token));
    };

    if (token) {
      const kakaoprofile = async() => {
        const profile = await getKakaoProfile();
        // console.log("profile:",profile);
        dispatch({
          type: KAKAOLOG_IN_REQUEST,
          data: profile
        })
      };
    }
  }

  return (
    <Container>
      <LoginButton onPress = {() => Login()}>
        <Label>카카오 로그인</Label>
      </LoginButton>
    </Container>
  );
};

export default Kakao;

1 个答案:

答案 0 :(得分:2)

您可以尝试创建另一个函数。假设 handleOrder 并使其异步,然后将所有等待放在那里。


const Login = () => {
  handleInOrder()
}

async function handleInOrder() {
try{
  const token = await getKakaoProfile()
  if(token){
   let data = await nextInOrder(token)
   //do a dispatch
   }
} catch(err){
  // handle the error
}
}


如果您需要任何帮助,请告诉我

相关问题