Trying to access array fetched from an API in global scope [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 25 days ago.
This post was edited and submitted for review 25 days ago.
I'm doing an API fetch and am trying to use the returned array of objects "stops" elsewhere in the global scope, however I cannot extract this array from the API fetch's scope after the .then() to use in the GLOBAL SCOPE because I am trying to use the array in other local scopes without calling the function in there.
i.e I would like to be able to use the array contained in variable stops in a separately scoped API call.
const fetchBusStopInfo = async () => {
try {
const url = new URL("https://data.edmonton.ca/resource/4vt2-8zrq.json")
url.search = new URLSearchParams ({
"$$app_token": "25u3nAznyYiBSLWIyQ4bmKnde",
"$limit": 100000
});
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.log(error)
return error;
}
}
fetchBusStopInfo().then((stopsArray)=> {
const stops = stopsArray
console.log(stops)
})
Is there a way to get around this so I can use the array found in const stops elsewhere?

Related

Javascript returned data from function which fetches an api [duplicate]

This question already has answers here:
How can I access the value of a promise?
(14 answers)
Closed 9 months ago.
I have the follwoing function which uses fetch to cal a restfull APi and get the output data which is in text format:
async function fetchText(url) {
let response = await fetch(url);
let data = await response.text();
console.log('data...',data);
return data;
}
The function execution of this script
mydata=fetchText(myurl);
console.log("mydata...........",mydata);
returns this out put
mydata........... Promise[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: ""6269A297-851B-4158-873B-66F068B73BCD""
data... "6269A297-851B-4158-873B-66F068B73BCD"
How to change the function so that its output is exactly what is displayed by the log instead of the Promise type ?
function that uses async keyword will always returns promise, so use following code to print value.
fetchText(myurl).then(data=>{ console.log(data) })

How to extract data from fetch? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a function loadData which attemps to fetch an array of customers. I wonder what is the best way to extract the data "outside"? Right now the only solution I can think of is using an external array and injecting it with data. I do not know however if this is the best practice as the test array is getting mutated in the process. What could an alternative solution be?
const test = [];
const loadData = (async () => {
const customersFetched = await fetch(customers);
const data = await customersFetched.json();
test.push(data);
})();
async function loadData() {
const customersFetched = await fetch(customers);
return await customersFetched.json();
}
const data=loadData();
loadData will return the response array.

Javascript JSON function parsing issue [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
Having a strange issue where im trying to parse some JSON for use with Chart.JS .. I can console log within the function and use the array so to say as expected but outside of that function even though i have made it a Global variable the array is empty after the function runs and i print it out to the console.
var data = {}
const api_url = "http://localhost:5000/"
var currentPage = window.location.href
currentPage = currentPage.split("/")
currentPage = api_url + currentPage[4]
console.log(currentPage)
async function getJson() {
const response = await fetch(currentPage);
data = await response.json();
console.log(data)
}
getJson()
console.log(data)
Well, you are executing an async function but you don't await.
So, instead of this:
getJson()
Use this:
getJson().then(_ => console.log(data))

How to return data from await/async loops? [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have several async http requests I need to make to an API to fetch some data. It's pretty simple to setup in a loop in a function like this:
async function fetchData() {
let data = {}
for (const asset of someAssets) {
try {
data[asset.id] = await library.fetchSomeData(asset.id)
} catch (err) {
console.error(err)
}
}
return data
}
let data = fetchData()
console.log(data)
The problem here is that the last console.log(data) comes back as a pending Promise instead of the data. How do I fix this issue? Do I need to wrap my "main" code (at the bottom) in a async function as well? At what point does my entire project just need to wrapped around a async function?

Is it possible to save the response data from a Fetch to a variable to use later? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
Using the Fetch API I'm making a GET request to an API endpoint which returns an object. I would like to save this object to use later, outside of the Fetch, but it seems that when I do, the variable I've initialized returns undefined.
I have initialized a variable before the fetch which I set equal to the response data inside a .then call:
const getObject = (convoId) => {
let url = base_url + `/${convoId}`
let convo; //<-- initializing the variable
fetch(url, { method: "GET", headers })
.then(response => response.json())
.then(data => convo = data)
.then(() => console.log(convo)) //<-- successfully logs the data
.catch(err => {
console.error(err);
});
console.log(convo); //<-- logs undefined
};
Because I initialized convo before the fetch and assigned it the value of the data object from the response, I expected that convo would be assigned - especially because logging convo within the .then call was successful.
But it appears it is only valid inside the fetch. I'm probably overlooking something small, so any helpful feedback is very welcome!

Categories