Я получаю `Не могу использовать ключевое слово 'await' вне функции asyn c внутри функции Asyn c. React-native - PullRequest
0 голосов
/ 18 января 2020

У меня проблема с asyn c, ожидаю выполнения функции AsyncStorage в моем приложении React-native. Я получаю ошибку:

Can not use keyword 'await' outside of a async function

Как вы можете видеть ниже, очевидно, что ожидание находится внутри функции. Что я делаю не так, чтобы получить эту ошибку?

_retrieveData = async function (location) {
  try {
    var index = await AsyncStorage.getItem(location, (err, result) => result).then(result => result).catch(error=>console.log(error))
    if (index !== null) {
      return JSON.parse(index)
    }
  } catch (error) {
    return null
  }
};

_storeData = async function(location, value) {
  try {
    await AsyncStorage.set(location, JSON.stringify(value));

  } catch (error) {
    console.log(error)
  }
};

Ответы [ 2 ]

0 голосов
/ 18 января 2020

Использование функций стрелки ES6

const _retrieveData = async location => {
  try {
    let index = await AsyncStorage.getItem(location)
    if (index !== null) {
      return JSON.parse(index);
    }
  } catch (error) {
    return null;
  }
};

const _storeData = async (location, value) => {
  try {
    await AsyncStorage.set(location, JSON.stringify(value));
  } catch (error) {
    console.log(error);
  }
};
0 голосов
/ 18 января 2020

Сделай их стрелками функций

_retrieveData = async location => {
  try {
    let index = await AsyncStorage.getItem(location)
    if (index !== null) {
      return JSON.parse(index);
    }
  } catch (error) {
    return null;
  }
};

_storeData = async (location, value) => {
  try {
    await AsyncStorage.set(location, JSON.stringify(value));
  } catch (error) {
    console.log(error);
  }
};

...