I am trying to fetch a javascript file and return the response object as an array. My javascript file is simply an array like ["1", "2", "3", ...] Here is my code right now:
function getNames() {
let data = fetch('/path/to/file')
.then((response) => response.json())
.then(data => {
console.log(data);
return data()
})
.catch(error => {
return error;
});
}
I need to find a way to use the data variable outside of the function. How can I do this?
You are using node.js, so you can use require() if you use module.exports
./someFile.js
module.exports = {
foo: "bar"
}
./otherFile.js
const data = require("./someFile.js")
console.log(data.foo) // "bar"
If you are asking to get a simple array or object from a file, you should be using .json files, and use require() just like in the first example. If you want to get the current data, rather than the data you get when you first require it, use the fs module
./array.json
[
"1",
"2",
"3"
]
./otherFile.js
const fs = require("fs")
const data = JSON.parse(
fs.readFileSync("./array.json", "utf8")
)
console.log(data) // [ "1", "2", "3" ]
let data = [];
(
function() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => {
data = [...json]
})
}
)();
// this is outside - might be empty, if the response does
// not arrive under 3 seconds
setTimeout(() => {
console.log("data in setTimeout", data)
}, 3000)
If you want to update the state of your app reactively (based on whether the area has arrived or not), then you should use a reactive library/framework like React, Vue, Angular or Svelte. (Of course, you can create your own reactivity system, but that might be limiting later.)