Return of async functions

Asked

Viewed 174 times

1

I’m using the AsyncStorage to save the value of some tokens with the following code:

Asyncstorage.js:

import AsyncStorage from '@react-native-community/async-storage';

setValue = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value)
    } catch(e) {
      console.log(e)
    }
  console.log('value set')
}

getMyValue = async (key) => {
  try {
    const value = await AsyncStorage.getItem(key)
    console.log(value)
    return value
  } catch(e) {
  console.log(e)
}

App.js:

import store from './AsyncStorage'
const str = new store
setValue('1', 'teste')
console.log(getMyValue('1'))

Only that the function’s Return is happening before the await returns with the data, because in the React Native console is in the following order:

//essa linha é do console.log(getMyValue('1'))
LOG  {"_40": 0, "_55": null, "_65": 0, "_72": null}
LOG  value set  // essa é o console.log('value set')   
LOG teste // essa é o console.log(value)

I tried to give Return right when running Asyncstorage.getItem(key) like this:

return await AsyncStorage.getItem(key)

But you make the same mistake.

1 answer

2


I found out what was going on:

In the archive AsyncStorage.js I had the function async with await of the return of storage, but in the App.js file I had a synchronous assignment, ie, it performed the assignment before the function getMyValue could return with the value of "value"

To fix the problem I created an asynchronous function in the assignment as well, as follows:

str.setValue('1', '2')
const f = async () => {
  console.log(await str.getMyValue('1'))
}

The only problem is that all handling of this data will have to be done within the async function, whereas if you return the function as follows:

str.setValue('1', '2')
const f = async () => {
  return await str.getMyValue('1'))
}
console.log(f())

It will generate the same problem, because the attribution is outside the asymchronism.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.