I’m totally newbie in JavaScript … I have this code:
const MMKV = new MMKVStorage.Loader().initialize();
async function getData() {
let role = await MMKV.getStringAsync("role");
if (role === "distribuidor") {
consumerKey = Constants.Keys.distributorConsumerKey;
consumerSecret = Constants.Keys.distributorConsumerSecret;
return [consumerKey, consumerSecret];
}
};
let data = getData();
let consumerKey = data[0];
let consumerSecret = data[1];
export default {
WooCommerce: {
url: "https://xxxxx.com/",
consumerKey,
consumerSecret,
},
But consumerKey and consumerSecret are always undefined…
I know (I think) it’s because the getData () function is asynchronous, and when I save the data in the variables, the function is not finished executing yet, but I don’t know how to do it right. I have been quite a while, I have read about the callback functions, the promises, … And I think the solution may go there, but I am very lost.
I would greatly appreciate a help. Thank you so much everyone.
Regards.
2
Answers
getDate() return a promise you have to add .then and move your code inside it
Once you have started doing something asynchronous, your code can’t return results synchronously.
You have multiple options to solve this problem (neither will ‘synchronize’ the code):
Use the Top-level await proposal (currently at Stage 3). That’s the only way in which you can properly export things asynchronously. If this feature isn’t currently available to you, you can transpile your code with tools like Babel.
Use an IIAFE (Immediately Invoked Async Function Expression) wrapper:
You’ll have to export a promise, not a value, like this:
then
it!You’ll also have to export a promise, not a value, like this: