Strange return even with Async/Await

Asked

Viewed 84 times

-3

I have the following functions in common.js

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

const getData = async () => {
    try {
        const jsonValue = await AsyncStorage.getItem('@storage_Key')
        return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (e) {
        // error reading value
    }
}

const storeData = async (value) => {
    try {
        const jsonValue = JSON.stringify(value)
        await AsyncStorage.setItem('@storage_Key', jsonValue)
    } catch (e) {
        // saving error
    }
}

export { getData, storeData }

And I have the following functional component Auth.js:

import React, { useState } from 'react'

import axios from 'axios'

import { serverLogin, showError, storeData, getData } from '../common'

console.log(getData())

const initialState =
{
    email: '',
    password: '',
    save: false
}

export default props => {
    const [state, setState] = useState(initialState)

    const signin = async () => {
        try {
            storeData(state)

            const res = await axios.post(serverLogin, {
                email: state.email,
                password: state.password
            })

            props.onStoreToken(res.data.token)
        } catch (e) {
            showError(e)
        }
    }

    return ( 
       ...
    )

}

As you can see above, I put a.log (getData()) console to check the content saved in Asyncstorage, but I only get this strange return:

{"_U": 0, "_V": 0, "_W": null, "_X": null}

So I’ve researched this is related to a mistreatment with async/await, but I can’t pinpoint where part of the code. Can someone help me?

2 answers

1

What you’re logging in is the prototype of a Premomise.

When you prefix it async in a function, it must return a precedent. The return of this function will then be the value by which the Precedent will be solved.

If you want to enter the value for which this variable is resolved, you must use await, and to use await, you must be inside an async function.

Another option you have is to use the .then after calling async, for example...

async getData = () => {
    return "some data";
}

myFunction = () => {
    getData().then(data => console.warn(data));
}

async myOtherFunction = () => {
    const data = await getData(); //uso await porque getData retorna uma promise
    console.warn(data);           //data agora contém o valor pelo qual a promise resolveu
}

These two examples produce basically the same result. There is still a difference between them in the way in the execution cycle, but the result is basically the same.

-1


I found the solution to the problem in https://stackoverflow.com/questions/63798588/reactnative-asyncstorage-returns-weird-values

It seems I have to use async/await also in the method call:

useEffect(async () => console.warn(await getData()), [])

Actually I did not understand why I had to wait for Dinovo when invoking getData(), since in the same I already wait, in case someone wants to answer that is just say!!!

Anyway that solved the problem.

Browser other questions tagged

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