✅ – BIOLOGY SCIENCE – 11-02 Jul 28

this is my code
const fs = require('fs');
const x = [1, 2, 3 ...]; // array consisting of numbers
const temp = []; // empty array

x.forEach((item) =>
{
fx(item).then((promiseData) =>
{ // fx is a function returning a promise

fs.writeFileSync('path/to.file', promiseData);

if ( (item / 2).toString().includes('.') ) {
temp.push(item);
}

});
});

fs.writeFileSync('path/to/differnet.file', JSON.stringify(temp, null, 4));
const fs = require('fs');
const x = [1, 2, 3 ...]; // array consisting of numbers
const temp = []; // empty array

x.forEach((item) =>
{
fx(item).then((promiseData) =>
{ // fx is a function returning a promise

fs.writeFileSync('path/to.file', promiseData);

if ( (item / 2).toString().includes('.') ) {
temp.push(item);
}

});
});

fs.writeFileSync('path/to/differnet.file', JSON.stringify(temp, null, 4));
for some reason the content of path/to/different.file is just an empty array i have tried logging the temp array after the forEach loop, it is not empty, but when i try to write the file, it doesnt work properly any fixes ?
3 Replies
ScriptyChris
ScriptyChris2y ago
forEach is unaware of async code inside You should rather use Promise.all + array.map() Something like that
const temp = await Promise.all(
x.map((item) => {
return fx(item)
.then((promiseData) => { // fx is a function returning a promise
fs.writeFileSync('path/to.file', promiseData);

if ( (item / 2).toString().includes('.') ) {
return item;
}
});
})
);
const temp = await Promise.all(
x.map((item) => {
return fx(item)
.then((promiseData) => { // fx is a function returning a promise
fs.writeFileSync('path/to.file', promiseData);

if ( (item / 2).toString().includes('.') ) {
return item;
}
});
})
);
RelativPerspektiv
Ohok I'll give it a try awesome, it works thank you
reactibot
reactibot2y ago
This question has an answer! Thank you for helping 😄 If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1002169170571563030 This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1002169170571563030