[英]Whats the best way to call one async function inside another?
I'm making simple authentication on React Native app using AsyncStorage to keep token. 我正在使用AsyncStorage在React Native应用程序上进行简单身份验证以保留令牌。 And after fetch I need to call AsyncStorage to save the token I've received.
在获取之后,我需要调用AsyncStorage来保存我收到的令牌。 I'm looking for an advice: what is the best-practice way to do it?
我正在寻求建议:最佳实践方法是什么?
function login(username, password) {
const requestOptions = {
"method": "POST",
"headers": { "Content-Type": "application/json" },
"body": JSON.stringify({ username, password })
};
return fetch(`${BASE_URL}/authenticate`, requestOptions)
.then(response => {
return response.json();
})
.then(res => {
AsyncStorage.setItem("@Storage:key", user.token).then();//doing smth);
return res;
});
}
You would await with all the async requests 您将等待所有异步请求
async function login(username, password) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
}
const res = await fetch(`${BASE_URL}/authenticate`, requestOptions)
const response = await response.json();
await AsyncStorage.setItem('@Storage:key', user.token)
return response.msg
}
Generally, chaining Promises is one of the cleanest ways. 通常,链接Promises是最干净的方式之一。 For example, something like:
例如,类似于:
return fetch(url)
.then(res => res.json())
.then(res => AsyncStorage.setItem('key', token).then(res => res.msg));
Pretty much how you had it. 几乎你是如何拥有它的。
If you can use Babel to transpile, using async/await
can make it even nicer: 如果你可以使用Babel进行转换,使用
async/await
可以使它更好:
const res = await (await fetch(url)).json();
await AsyncStorage.setItem('key', token);
With await
and async
, as long as your await
on a Promise
, you can then treat them the same as non-async code. 使用
await
和async
,只要await
Promise
,就可以将它们视为非异步代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.