I'm trying to get information (true/false) from AsyncStorage in a function and create a string which is importent to fetch data in the next step. My problem is, the function is not finished until the string is required.
I tried many solutions from the internet like async function and await getItem or .done() or .then(), but none worked out for me.
The current behaviour is that the console displays first "channel required: " than "channel: channel_id0".
Try this instead. Async functions and Promises can be tricky to get right and can be difficult to debug but you're on the right track.
Aspects in your question are unclear:
You don't say when
this.state.firstValue
is set, and how that relates to what you are trying to accomplish.You have a
for-loop
where you could be setting the same value multiple times.There are somethings we can do to make your code easier to understand. Below I will show a possible refactor. Explaining what I am doing at each step. I am using
async/await
because it can lead to much tidier and easier to read code, rather than usingpromises
where you can get lost in callbacks.'not'
.Promise.all
, this part is important as it basically gets all the values for each of the keys that we just found and puts them into an array calleditems
items
array has akey
and avalue
property.items
so that only the ones with aitem.value === 'true'
remain.items
so that only the ones with aitem.value !== 'true'
remain. (this may be optional it is really dependent on what you want to do)Here is the refactor:
You would call this function as follows:
Although the above will work, it will not currently return a value as you haven't made it clear which value you wish to return. I would suggest you build upon the code that I have written here and update it so that it returns the values that you want.
Further reading
For further reading I would suggest these awesome articles by Michael Chan that discuss
state
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
I would also suggest taking some time to read up about
async/await
andpromises
https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8
And finally this article and SO question on
Promise.all
are quite goodhttps://www.taniarascia.com/promise-all-with-async-await/
Using async/await with a forEach loop
what if you wrap the
_getFetchData()
in a Promise? This would enable you to useOtherwise the console.log won't wait for the execution of the _getFetchData(). This is what the console.log is telling you. it just logs the string. the variable is added after the async operation is done.
UPDATE
I would try this:
maybe you must change the
this.state.channels !=== undefined
to an expression that's matches the default value ofthis.state.channels
.