This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Returning array populated in loop by async function
(3 answers)
Closed 6 months ago.
I want to run async method and wait for the array.
My method preloadVideos doesn't return the array. What am I doing wrong?
When I console.log preloadedVideos in then section everythign is fine, but not returning. What should I change?
readyVideos is running only once and return [], but when the responses came and array has some values like [video1, video2, ...] then readyVideos is not returning, why?
Why my question is closed? Not even try to let people help me
I found your articles but it is not the same context? Why you don't let people grow?
useEffect(() => {
const preloadVideos = async (videos) => {
const preloadedVideos = [];
await videos.forEach((url) => {
axios({
url: url.url,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const downloadedVideo = window.URL.createObjectURL(new Blob([response.data]));
preloadedVideos.push({ url: downloadedVideo });
});
})
return preloadedVideos;
};
if (url && isNotSingleVideo) {
const readyVideos = preloadVideos(url);
if (readyVideos.length === url.length) {
console.log('I AMA READDYY', readyVideos, url);
setVideosToWatch(readyVideos);
}
}
}
}
Related
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 2 months ago.
Main function
export async function postData(TVMID) {
const data = await FetchingData(TVMID)
// regex the year
const rex = /^[0-9]{4}/g;
let country;
let network;
let geners = await CheckGenderIfExist(data.genres).then(genx => genx)
more code....
}
Check if data exist function
export async function CheckGenderIfExist(genders) {
let listOfGenders = [];
if (Array.isArray(genders)) {
genders.forEach(gen => {
axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/genders?filters[$and][0][Name][$eq]=${gen}`)
.then((response) => {
if (response.data.data.length == 0) {
AddTVGenders(gen)
} else {
listOfGenders.push(response.data.data[0].id)
}
});
})
} else {
axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/genders?filters[$and][0][Name][$eq]=${genders}`)
.then((response) => {
listOfGenders.push(response.data.data[0].id)
});
}
return listOfGstenders;
}
Add missing data function
export async function AddTVGenders(gen) {
await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/api/genders`, {
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
"data": {
Name: gen,
}
})
CheckGenderIfExist(gen)
}
Im' using strapi v4.5 with nextjs v13, while tring to post data for some of the relation fields , i have to check if the data exist if not, i create it then get the id then add it to the main post function
This is what i came up with but it return empty array
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 months ago.
I would have a simple question but can't figure it out the answer with Node.JS. Here it is : I got a file with multiple function and I would like to use the return of the first inside the second :
//The first function
const Function1 = (req, res) => {
var axios = require('axios');
var config = {
method: 'get',
url: 'xxxxx.json',
headers: {
//...
}
};
axios(config).then(function(response) {
const array = response.data.datas
return Promise.all(Object.values(array).map(entry => {
return entry.id
}))
}).then(function(response) {
//I got an array with infos
return response
}).catch(function(error) {
console.log(error);
});
}
const Function2 = (req, res) => {
const previousResult = function1()
//Undefined
console.log(previousResult)
}
How should I proceed ?
Thanks a lot
Do you need to call the function?
function1()
Update:
It looks like you added to your question. This now seems to be an issue with async functions. You should look up how to use promises, and async await. It's a bit too complex to describe here, and there are a lot of tutorials about it. The short answer is that when you return inside of a promise, it doesn't return from the outer function1. You could probably test this in your code by putting an explicit return at the end of function1 and you'll see that in console.log().
This question already has answers here:
How can I access the value of a promise?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm building backend to fetch pictures of users I follow. The function below is a helper function that takes an array of user IDs to map against it to get their pictures. This function returns a single promise.
const getFeedPhotos = async (followingArr) => {
const promises = followingArr.map(async userId => {
await Photo.find({userId: mongoose.Types.ObjectId(userId)});
});
const x = Promise.all(promises);
return x;
};
Code below is the router itself where I am invoking my helper function.
photoRouter.get(
'/feed',
expressAsyncHandler(async (req, res) => {
const following = req.body.following;
if (following) {
const response = getFeedPhotos(following);
console.log(response);
} else {
res.status(400).send({ message: '"Following" is not provided.' })
}
})
);
The problem is that response equals to Promise { <pending> }. I need this promise to resolve in order to send it to my client. My question is how do I do that? I do realize that it has to do with some blunder of mine and stems from my misunderstanding of the whole async concept per se. I was trying to make some research but none of the solutions worked for me.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have the following Vue methods. When clicking on the edit button, onEditUserPermissions is called. That function also fetches this.fetchUserPermissions. The request does finish, and a response is received.
methods:{
onEditUserPermissions(item){
this.userCheckbox = true
let user = item.id
this.selectedUser = item.id;
this.fetchUserPermissions(user)
for (let x of this.assignedUserPermissions){
console.log('assigned',x.id)
this.selectedUserItems.push(x.id)
}
this.editedIndex = 'users'
this.dialog = true
},
fetchUserPermissions(user){
this.$axios.get('/permissions/assigned/user/'+user)
.then(res => {
this.assignedUserPermissions = res.data
})
},
}
When I first click, the for of loop doesnt work, it doesnt iterate, however, when clicked again, it works. I may be too close to the project but can anyone tell why?
You need to wait for the http promise to resolve before attempting to access the data. It works the second time because then it uses the result from the first fetch.
First, you need to return the promise from fetchUserPermissions, and then you need to wait for that promise in onEditUserPermissions:
methods: {
async onEditUserPermissions(item){ // `async` keyword
this.userCheckbox = true
let user = item.id
this.selectedUser = item.id;
await this.fetchUserPermissions(user); // awaiting the promise
for (let x of this.assignedUserPermissions){
console.log('assigned',x.id)
this.selectedUserItems.push(x.id)
}
this.editedIndex = 'users';
this.dialog = true
}
fetchUserPermissions(user){
return this.$axios.get('/permissions/assigned/user/'+user) // return the promise
.then(res => {
this.assignedUserPermissions = res.data
})
},
}
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 3 years ago.
usersList is a valid array with string values,
User.findById(userId) returns an user as expected.
I think the problem lies in the block of scope because forEach method and FindById method works perfect.
I've tried many methods of array returning each value. (e.g. map and filter)
I've read many documents about advanced MongoDB technique, the block of scope and array methods.
const usersList = camp.usersList;
let users = [];
usersList.forEach((userId) => {
User.findById(userId, (err, user) => {
if(err) return res.redirect('/admin/db');
users.push(user);
})
})
console.log(users);
The output should be [user1, user2, ...], not [].
async () => {
const usersList = camp.usersList;
const users = [];
for (var userId of usersList) {
const user = await User.findById(userId).exec();
if (!user) return res.redirect('/admin/db');
users.push(user);
}
console.log(users);
}
For better Performance, you can use this below code, it will not wait for individual request to complete, it will make parallel calls and hence increase the performance
async ()=> {
try {
const users_promise = usersList.map(userid => User.findById(userid).exec())
const users = await Promise.all(users_promise);
} catch(error) {
res.redirect('/admin/db');
}
}
Use array of promises instead
const userPromises = usersList.map(userid => User.findById(userid))
Promise.all(userPromises).then(users => console.log(users))
.catch(() => res.redirect('/admin/db'));