非异步功能中的AsyncStorage

时间:2019-02-21 18:57:30

标签: javascript reactjs

以下代码:

 _loginAsync = async () => {
    fetch('localhost:3000/login')
      .then((response) => response.json())
      .then((responseJson) => {
        await AsyncStorage.setItem('my-item', responseJson.item);
        this.props.navigation.navigate('Home');
      })
      .catch((error) => {
        console.error(error);
      });
  }

引发错误:Can not use keyword 'await' outside an async function

哪种是使my-item升值的正确方法?

2 个答案:

答案 0 :(得分:2)

您的.then回调未标记为async,只有外部_loginAsync函数被标记。

 _loginAsync = async () => {
    fetch('localhost:3000/login')
      .then((response) => response.json())
      .then(async (responseJson) => {
        await AsyncStorage.setItem('my-item', responseJson.item);
        this.props.navigation.navigate('Home');
      })
      .catch((error) => {
        console.error(error);
      });
  }

也就是说,在这里混合所有.thenawait形式似乎很奇怪。

仅使用异步/等待

我认为这是最易读的版本。我们只是使用async / await直接等待获取,而不使用其诺言。

 _loginAsync = async () => {
    try {
        const response = await fetch('localhost:3000/login');
        await AsyncStorage.setItem('my-item', response.json().item);
        this.props.navigation.navigate("Home")
    } catch(error) {
        console.error(error);
    }
  }

直接使用承诺

您可以(几乎)始终将异步函数用作返回promise的普通函数。因此,我们无需awaitAsyncStorage.setItem设置为then,而只需将其承诺从 _loginAsync = () => { fetch('localhost:3000/login') .then((response) => response.json()) .then((responseJson) => AsyncStorage.setItem('my-item', responseJson.item)) .then(() => this.props.navigation.navigate('Home')) .catch((error) => { console.error(error); }); } 中返回即可。

var a=[]; //declaring an array a.
var num=snapshot.numChildren(); //storing number of children in var num.
a.push(snapshot.val()); // pushing data in the array.
if (a.length==num){ //checking if length of array is same as number of children.
a.reverse(); //reversing the array elements.
for(i=0; i<num; i++){
a[i].name;//this will sort the data in descending order.
}
}

答案 1 :(得分:-2)

如果必须使其适用于代码,请为await出现async的块创建匿名函数。

_loginAsync = async () => {
    fetch('localhost:3000/login')
      .then((response) => response.json())
      .then(async (responseJson) => {
        await AsyncStorage.setItem('my-item', responseJson.item);
        this.props.navigation.navigate('Home');
      })
      .catch((error) => {
        console.error(error);
      });
  }

但是我更喜欢这是一种更好的方法,并且看起来更具可读性。尝试使用此代码。

_loginAsync = async () => {
    try {
        const response = await fetch('localhost:3000/login');
        const responseJson = response.json()
        await AsyncStorage.setItem('my-item', responseJson.item);
        this.props.navigation.navigate('Home');
    } catch (error) {
        console.error(error);
    }
}