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.
Related
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?
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))
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
In my code i have an async function that retuns an object i have to work with it outside the function but i dont really know how to assign it to a variable, I know this post might be a duplicate but i read the others and tried and it doesn't work.
async function name(url) {
//function
return {
item1:{ ....},
item2:{....}
}
}
let p = name(url);
console.log(p);
it returns in the console:
Promise { <pending> }
but it doesn't log the output
How can i fix that?
Promises are async. You need to get the result using
A callback, specified to the then method of the promise.
name(url).then(p => console.log(p))
Or use an async context and use the await keyword:
(async(){
let p = await name(url);
console.log(p);
})();
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?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I want to extract an array from the public API, and all I'm receiving is a promise. How can I return the array from the API, outside my function?
Please have a look at the code I'm trying to implement:
var getMov = function() {
return fetch('http://localhost:8080/api/projects')
.then((response) => response.json())
.then((responseJson) => {
JSON.parse(responseJson.movies);
return responseJson.movies;
})
};
console.log(getMov());
Let me know if you have any ideas, how to solve this promise issue.
You just have to use the then method again.
getMov().then(function(movies) {
// do smth with movies
});
According to the promises specs the argument of the onFulfilled function will be the returned value from the last exectuted onFulfilled method, which is your case return the movies.