I can't make this work...it's says: await is a reserved word. Yes, of course it is...and I'd like to use it :)
What's wrong ?
export const loginWithToken = async () => { return dispatch => { dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true}) let storedData = await ReadFromLocalDB('user') console.log(storedData) if (!storedData) { invalidToken(null, dispatch) } else { storedData = JSON.parse(storedData) SessionLoginWithToken(storedData.session.token).then(res => { console.log(res) loginSuccessfully(res, dispatch, true) }) } } }
My ReadFromLocalDB
function looks like this:
export const ReadFromLocalDB = async (key) => { return AsyncStorage.getItem(key) }
It returns a promise
The syntax is as follow: you must declare a function to be async : const asyncFunction = async () => { // This is a good start } // or const asyncFunction = async function(){ // Old school function keyword? I like it! }
Use named exports to export constants in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported constants can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.
return dispatch => {...}
needs to also be async
I believe. Right now, only the top level function is async
, not the nested one.
// This function is async export const loginWithToken = async () => { // This one is not though which means it can't use await inside // return dispatch => { // Instead it should likely be: return async dispatch => { dispatch({type: SESSION_LOGIN_IN_PROGRESS, payload: true}) let storedData = await ReadFromLocalDB('user') console.log(storedData) if (!storedData) { invalidToken(null, dispatch) } else { storedData = JSON.parse(storedData) SessionLoginWithToken(storedData.session.token).then(res => { console.log(res) loginSuccessfully(res, dispatch, true) }) } } }
With export and import we are suggested to follow the model:
To define and export a function in the file myFile.js:
export const request = async (arg1, arg2) => { try { const response = await fetch('https://api.com/values/?arg1=' + arg1 + '&arg2=' arg2); const json = await response.json(); console.log(json); } catch (e) { console.log('We have the error', e); } }
To import and apply the function:
import {request} from './myFile' request(arg1, arg2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With