Javascript 在一个异步函数中调用另一个异步函数的最佳方法是什么?

Javascript 在一个异步函数中调用另一个异步函数的最佳方法是什么?,javascript,reactjs,react-native,promise,async-await,Javascript,Reactjs,React Native,Promise,Async Await,我使用AsyncStorage在React本机应用程序上进行简单身份验证以保留令牌。在获取之后,我需要调用AsyncStorage来保存我收到的令牌。我在寻求一个建议:什么是最好的实践方法 function login(username, password) { const requestOptions = { "method": "POST", "headers": { "Content-Type": "application/json" }, "body": JS

我使用AsyncStorage在React本机应用程序上进行简单身份验证以保留令牌。在获取之后,我需要调用AsyncStorage来保存我收到的令牌。我在寻求一个建议:什么是最好的实践方法

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;                    
    });
}

一般来说,链接承诺是最干净的方式之一。例如,类似于:

return fetch(url)
  .then(res => res.json())
  .then(res => AsyncStorage.setItem('key', token).then(res => res.msg));
和你的情况差不多

如果您可以使用Babel进行传输,那么使用
async/await
可以使传输变得更加出色:

const res = await (await fetch(url)).json();
await AsyncStorage.setItem('key', token);

使用
wait
async
,只要您的
wait
符合
Promise
,您就可以将它们视为非异步代码。

您将等待所有异步请求

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
}

您是否必须等待
AsyncStorage.setItem(“@Storage:key”,user.token).then()返回前?您忘记了
login
函数中的顶级
async
关键字。我假设
const-response
应该是
const-user
@RicoKahler-const-response可以是const-user如果OP有意的话,我写了OP在回答中提到的内容,谢谢你提醒我async关键字。当我开始写答案的时候,我的脑海里已经有了答案,但我忘记了