✅ – 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 ?
S
ScriptyChris629d 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;
}
});
})
);
R
RelativPerspektiv629d ago
Ohok I'll give it a try awesome, it works thank you
UU
Unknown User628d ago