I want to export a variable, but it is being exported empty. I need this to wait for the data to be inserted and then it will be exported, but I'm not able to do it
let eventGuid = 0
let INITIAL_EVENTS = [];
let datas = "";
function getDatas(){
return fetch("http://localhost:3214/events")
.then((data) => data.json())
.catch((err) => console.log(err))
}
async function armazenar() {
datas = await getDatas();
}
async function api(){
await armazenar()
datas.forEach(element => {
INITIAL_EVENTS.push(element)
});
}
api()
export default INITIAL_EVENTS;
export function createEventId() {
return String(eventGuid )
}
CodePudding user response:
async function api(){
await armazenar()
datas.forEach(element => {
INITIAL_EVENTS.push(element)
});
}
api()
this function is an async function api(), but has no await api(). Idk if this solves your problem but you should fix it.
CodePudding user response:
First, some explanation about the export statement is necessary. What export is intended for is make code available to other files in the course of the build performed by node. What export won't do is provide values of variables to code in other files. In short, export
is not a dynamic feature which operates at runtime.
I would just export an async default function as follows.
let eventGuid = 0
function getDatas(){
return fetch("http://localhost:3214/events")
.then((data) => data.json())
.catch((err) => console.log(err))
}
export default async function () {
return await getDatas();
}
export function createEventId() {
return String(eventGuid )
}
Now you need to import our default function in some other file and then to execute it. Note that such an async function returns a promise. Your array with initial events is going to be the result returned by the latter promise when it resolves.