[英]How to return value of variable from async JS function in React Native
[英]How to assign the return of an async funtion to a variable in React Native
我尝试在JavaScript和React Native Framework中找到解决方法:
基本上,我正在尝试通过获取与API通讯,因此我设置了AsyncFunction:
class MyComponent extends React.Component {
async getToken(client_id, client_key, username, password) {
try {
let response = await fetch('https://expample.com/o/token/', {
method: 'POST',
body: JSON.stringify({
client_id: client_id,
client_secret: client_key,
grant_type: 'password',
username: username,
password: password,
})
});
let responseJson = await response.json();
return responseJson.access_token;
} catch(error) {
console.error(error)
}
}
...
}
但是现在我不知道如何调用该函数。
var token = getToken.token
只是给出语法错误,
'token': getToken.token
也没有办法。
您可以像这样将响应分配给组件的状态:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { token: null, };
}
async getToken(client_id, client_key, username, password) {
try {
let response = await fetch('https://example.com/o/token/', {
method: 'POST',
body: JSON.stringify({
client_id: client_id,
client_secret: client_key,
grant_type: 'password',
username: username,
password: password,
})
});
let responseJson = await response.json();
this.setState({ access_token: responseJson.access_token });
} catch(error) {
console.error(error)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.