This question already has answers here:
Wait until all jQuery Ajax requests are done?
(22 answers)
Why is my function returning Promise { <pending> } [duplicate]
(1 answer)
Closed 2 years ago.
How do I await the forEach function so that I can console.log(posters)?
let posters = [];
reviews.forEach(async (review) => {
// Get posters for reviews
await axios.get(`https://api.themoviedb.org/3/movie/${review.filmId}?api_key=${tmdb_api}&language=en-US`)
.then((data) => {
posters.push(data.data.poster_path)
})
.catch((error) => console.log(error))
})
console.log(posters)
Important: I cannot put the console.log inside the .then() because I need the filled posters array outside of the forEach function.
Related
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)
How can I access the value of a promise?
(14 answers)
Closed 7 months ago.
I found that it's not straight forward to filter a list of values of promises, so I tried the approach in this question (top answer).
The difference is, i'm using this inside useEffect in React.
My results array is empty outside of the async getData function:
// helper function
async function filter(arr, callback) {
const fail = Symbol();
return (
await Promise.all(arr.map(async (item) => ((await callback(item)) ? item : fail)))
).filter((i) => i !== fail);
}
useEffect(() => {
if (!stateData) {
let results = [];
async function getData() {
const res = await filter(data.slice(0, 5), async (item) => {
const boolRes = await myAsyncFunction(item);
return boolRes;
});
// results has data
results.push(...res);
}
getData();
console.log(results) // is empty, but results inside getData has data
}
}, []);
any idea how I can pull the data out of getData safely?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
async/await implicitly returns promise?
(5 answers)
Closed 2 years ago.
Get the value from a function in some other languages is simple like write return something
I can't get how to do it in JS from an async function.
const URL = `https://www.reddit.com/r/all.json`;
async function getPost() {
var list = [];
let response = await fetch(URL).then((res) => res.json());
let childList = await response.data.children;
childList.map((el) => {
let id = el.data.id;
let title = el.data.title;
list.push({
id: id,
title: title,
});
});
console.log(list);
}
var oo = getPost();
If you try the code like this everything work fine. But if to change console.log(list) inside getPOst() to return list and try to console.log(oo) nothing is showing
So... BIG thanks to #nick-parsons
that's the answer:
Oh, so a Promise is being shown. Your async function will wrap the >return value in a Promise, so that's expected. To "extract" the >value/list, you need to use .then(list => // use list here) on the >returned Promise. Or, if you're in a ES module, you can await the >Promise
This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 2 years ago.
Why protocols.usd is always returning 0?
I try making a dummy promise function to test it and it's working properly but it's not working with the await function.
async function addPrices() {
const balances = await getBalances();
await Promise.all(balances.map(protocols => {
protocols.usd = 0;
protocols.balances.map(balance => {
if (balance.underlying) {
balance.underlying.map(async token => {
let price = await getPrice(token.address);
protocols.usd += price.market_data.current_price.usd;
});
}
});
}));
return balances;
}
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 4 years ago.
I'm dealing with a JSON response that is coming from an API. The ResponseJson contains information about a category; the responseJson.name contains a category name (tested in the console). Now I want to add all category names and store them in the empty array, categoryNames. After the for loop, the categoryNames turns out to be empty when I try to print it in the console, and I'm not sure what I'm missing. Here is the code:
_getCategories = item => {
const categoryNames = [];
for (let category of item.categories) {
fetch('http://54.168.73.151/wp-json/wp/v2/categories/' + category)
.then(response => response.json())
.then(responseJson => {
var categoryName = responseJson.name;
categoryNames.push(categoryName);
})
.catch(error => {
this.setState({
isLoading: false,
isError: true,
});
console.error(error);
});
}
console.log(categoryNames);
};
This questions has been identified as a possible duplicate of another question, but the answers are the other question is about a $ajax call, while I am trying to use pure JavaScript. Are there any solutions with this syntax?
_getCategories = item => {
const categoryNames = [];
let fetches = [];
for (let category of item.categories) {
fetches.push(fetch('http://54.168.73.151/wp-json/wp/v2/categories/' + category));
}
Promise.all(fetches).then(res => {
/* do your stuff here */
})
};
You should you Promise.all to wait all fetches are done.
Can you try above code?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
as the title says I want to extract the variable status to be able to use it in another part of the code, is this possible?
RNAudioStreamer.status((err, status)=>{if(!err) console.log(status)})
Depending on the callback sync/async you can create a global variable or use promise.
let p = new Promise((resolve, reject) => {
RNAudioStreamer.status((err, status)=>{
if(!err) resolve(status); else reject(err);
})
});
// ...
p.then(status => {
// process status here
})