Update the global variable - javascript

My code snippet first:
let GLOBAL_VAR_A = 'string1';
let GLOBAL_VAR_B = 'string2';
let GLOBAL_VAR_C = []; // Empty array
let GLOBAL_VAR_D = []; // Empty array
...
start = async () => {
...
if(...) {
await updateNews(GLOBAL_VAR_A, GLOBAL_VAR_B, GLOBAL_VAR_C, GLOBAL_VAR_D);
console.log(GLOBAL_VAR_C); // => [] (empty) (NOT OK)
console.log(GLOBAL_VAR_D); // => [object Object] = nextNews (OK!!)
...
}
};
updateNews = async (sourcePath, webResource, previousNews, nextNews) => {
previousNews = await getPreviousNews(sourcePath, previousNews);
console.log('FFF = ' + previousNews); // => FFF = [object Object] (Ok)
...
nextNews.push({
id: i + 1,
title: justGottenNews[i].title,
url: justGottenNews[i].link
});
}
getPreviousNews = async (sourcePath, previousNews) => {
let data = await fs.readFileSync(sourcePath, 'utf8');
prevNews = previousNews.concat(JSON.parse(data));
return prevNews;
};
...
My question (issue) is the following:
When I call the function updateNews() I pass there some arguments - global variables. GLOBAL_VAR_C by default is an empty array which is passed to the updateNews() function. Further this variable is passed to getPreviousNews() function. This function returns a new array (prevNews) - concatenation of the empty one and received from the file.
Then I want to re-define a value of the variable previousNews. Inside the function updateNews() its value is correct (returned array).
How can I re-define a value of passed GLOBAL_VAR_C variable further? It should be equal to previousNews. But when I console log it still empty array is returned.
Interesting point is that nextNews is updated inside updateNews() function (method push()) and GLOBAL_VAR_D is updated as well

The solution for me was to update the Global variable with push() method inside updateNews()

Related

React: .map method statement returns undefined

I have the following function;
const ListallSpaces = newSubject.map(mySpaces => {
const urlToBeSplit = mySpaces.s
const onlySpaceNames = urlToBeSplit.split('/')[5]
const subject = []
return (
subject.push({subject: [onlySpaceNames]}),
console.log("subject", subject)
)
})
console.log(ListallSpaces)
if i console.log(subject) it returns an array containing a certain space, which is the value i need. However, if i console.log the ListallSpaces it returns undefined. is there a reason why?
Return something.
The below example will return an array with one element. That element will be an object.
const ListallSpaces = newSubject.map(mySpaces => {
const urlToBeSplit = mySpaces.s
const onlySpaceNames = urlToBeSplit.split('/')[5]
const subject = [{subject: [onlySpaceNames]}]
return subject
})
it is giving undefined as in your return statement your push command gives 1 and console.log gives you undefined.
To make this work you have to return the subject.
just try this.
subject.push({ subject: [onlySpaceNames] }); return subject;
Because console.log returns undefined.

How to access object provided by onloadedmetadata?

Im trying to acceess a value in a object resulting from onloadedmetadata. When I console log the entire object audioDuration i can see and access the contained value. When i console log the exact element AudioDuration.length it returns undefined.
var audioDuration = {};
convertedAudio.onloadedmetadata = () => {
audioDuration.length = convertedAudio.duration
};
console.log (audioDuration) // displays object {length: 25.547755}
console.log (audioDuration.length) // displays undefined
I want to use the value of AudioDuration.length directly and not the entire object.
your problem is due to the value of audioDuration is set only in callback and the console.log is used directly after onloadedmetadata so the console.log will run before the value is set. Two ways to fix that, one way is to do console.log inside onloadmetadata. The other way is to return a promise and await for the result.
const audioDuration = {}
const getDuration = () => new Promise(resolve => {
convertedAudio.onloadedmetadata = () => {
resolve(convertedAudio.duration);
}
})
getDuration().then(l => { console.log(l); audioDuration.length = l; })
Try this
var audioDuration = {};
convertedAudio.onloadedmetadata = () => {
if(convertedAudio.duration!=undefined){audioDuration.length = convertedAudio.duration}
};
console.log (audioDuration) // displays object {length: 25.547755}
console.log (audioDuration.length) // displays idk, u see what it does since i can't replicated convertedAudio

Which type of variable is created in the code below

In the code below is an iterator:
const cart = ['Product 0','Product 1','Product 2','Product 3','Product 4','Product 5','Product 6','Product 7','Product 8','Product 9','Product 10']
function createIterator(cart) {
let i = 0;//(*)
return {
nextProduct: function() {
//i:0; (**)
let end = (i >= cart.length);
let value = !end ? cart[i++] : undefined;
return {
end: end,
value: value
};
}
};
}
const it = createIterator(cart);
First I know a copy of the present state of the function's variables and the parameters are parsed.(Right?)...
And when you run
const it = createIterator(cart);
Is a property below created?
//i:0 (**);
Making it.next(); equivalent to
{
i:0;//state or value of i from createIterator() definition;
next : function(cart){
let end = (this.i >= cart.length);
let value = !end ? cart[this.i++] : undefined;
return {
end: end,
value: value
};
}
Or does state of the value of i in line (*) from the first code, Is what's what is modified?
Please if this point is not clear... let me know to explain better.
Calling the iterator will create an instance of i scoped to the createIterator function. The object returned from it will only have access to that specific instance of i, but i is not a property of the object returned. It only can access it due to the function scope.
You can see a little better how this works if we break your code down a little more simply:
function createIterator(cart, display) {
let i = 0;
return {
next: function() {
i++;
console.log(display + ' next: ', i);
}
};
}
const cart1 = [];
const cart2 = [];
const it1 = createIterator(cart1, 'cart1');
it1.next();
it1.next();
const it2 = createIterator(cart2, 'cart2');
it2.next();
it2.next();
Each instance of the iterator has a different copy of i and only the object returned from the iterator function can access it.

Javascript : String Array not updating

I am trying to pass updated testvar to ComponentX
let testvar = ["Test", "Test2"];
testvar.map(test => {
test = test + "Edited";
console.log(test);//updates here
return test;
});
console.log(testvar);//doesn't retrieve updated value
<ComponentX values={testvar}>
I am aware that console isn't asynchronous but I am also passing this updated value to a component,
but original gets passed.
I tried to wrap this update as async function, like below,
let testvar = ["Test", "Test2"];
const updateFunc = async()=>{
await testvar.map(test => {
test = test + "Edited";
console.log(test);//updates here
return test;
});
}
const updatedvalues = updateFunc();
<ComponentX values={updatedvalues}>
I receive errors as promise String[] isnt acceptable on ComponentX.
Any Leads would be helpful.Thanks!
You treat to the strings as there are mutable, but actuality there not. In this case you need to update array by index
let testvar = ["Test", "Test2"];
testvar.forEach((test,i) => {
testvar[i] = test + "Edited";
console.log(test);//updates here
});
console.log(testvar);
or created a new one
testvar = testvar.map(test => {
test = test + "Edited";
console.log(test);//updates here
return test;
});

Javascript: Array of objects, changing value in each object asynchronously

So, I know this has been asked before and I have tried other answers like .map, (function(post){ async })(value), and I am still stuck...
so, I have an array of objects and a for loop:
var postsData = [{thumbnail: www.website.com/image.jpg}, {thumbnail: www.website.com/image.jpg}, {thumbnail... etc}];
for (let i = 0; i < 3; i++) {
let thumbnail = postsData[i].thumbnail;
Cloudinary.uploader.upload(thumbnail, function(result){
// not sure what to do here
// result comes back as an object, and I want to change each thumbnail in
// the postsData array to be result.public_id
}, {transformation:[{}]});
} // go through all the items in the array
// do something with "updated" postsData array
An example would really help, as obviously, getting the values changed involves some async functions.
Set "thumbnail" property of object in array to result.public_id. Create a function where expected parameter is current object within postsData array, set "thumbnail" property of object by passing function reference to upload function, passing current object of array prop object utilizing Function.prototype.bind()
var len = postsData.length;
var n = 0;
function handleData(result, prop) {
prop["thumbnail"] = result_public.id;
if (++n === len) complete(postsData);
}
function complete(data) {
console.log(data, postsData);
}
for (let prop of postsData) {
Cloudinary.uploader.upload(
thumbnail
, handleData.bind(null, prop)
, {transformation:[{}]}
);
}
plnkr http://plnkr.co/edit/SSyUG03pyAwXMVpHdGnc?p=preview
From what I understand, you are trying to loop through an array and do async function on each of its element. What I would do is to use Promise.js (see enter link description here). So the code would look something like this:
// create an array for the promises
const PromiseArr = [];
postsData.map(d => {
PromiseArr.push(
// do async actions and push them to array
new Promise((resolve, reject) => {
Cloudinary.uploader.upload(thumbnail,(result) => {
// return the result
resolve(result);
});
})
);
})
// do all async actions and store the result in result array
const result = PromiseArr.all();

Categories

Resources