JavaScript Array result disappear [duplicate] - javascript

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)
Closed 6 years ago.
I'm writing a function that pass in a string called "term" to search in my MongoDB, then add its results to an existed empty array of results called "result[]":
var searchAndAddToResults = (result, term)=> {
Place.find({ $or: [
{name: term}, {category: term}
] }, places=> {
for (let i in places) {
if (!itemExists(result, places[i].toObject())) {
result.push(places[i].toObject())
}
}
console.log(result) // result isn't empty, which is good
})
console.log(result) // result is empty, which is bad and weird
return result // this returned result is also empty, THIS is the real problem
}
Can anyone help me with restructuring this code to get it work? Thanks

These calls are asynchronous - which is why you are getting results in succcess callback of Place.find() and finding one outside of the method. Because as soon as Place.find() is called the next line is executed. So it'll be great if you learn to work with these asynchronous calls of javascript.

Related

Trouble returning value from an Axiois get request React App [duplicate]

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 6 months ago.
I am fairly new to web dev/react/js but I have been trying to request data from the backend using this code, and I can't seem to return the correct value. In the code below, it still returns 10 rather than setting the "hey" variable to the JSON data I am looking for. I'm a little out of my depth but have been searching for solutions, any help welcome!
function getViews() {
let hey = 10;
axios.get("http://localhost:8000/views")
.then((response) => {
hey = JSON.stringify(response)
return hey
//This return statement doesn't get called
})
.catch((error) => {
console.error(error);
})
return hey
}
enter image description here

my object is modified inside a function that has a promise even if function returned [duplicate]

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)
console.log() async or sync?
(3 answers)
Closed 8 months ago.
i have the following function that should return a result object
function checkRegisteredStatus(addr)
{
let result ={status:"",registrationType:""};
instance.methods.isRegistered(session.id,addr).call().then((receipt)=>
{
let {status,registrationType}= receipt;
result["status"] = status;
result["registrationType"]= registrationType;
});
return result;
}
i want to use this function like this:
let result = checkRegisteredStatus(addr)
i have three problems :
1- when i used async/await pattern on isRegistered() method like this:
let result = await instance.methods.isRegistered(session.id,addr).call();
return result;
result object would be a promise with unfulfilled status, which is wired since the purpose of await is to return the result of the resolve callback, and this is the first time that happens to me, i did async/await before and it always returns the final result not a promise. why is this happening?
2- due to the first problem i had to re-write my function the old way which is using.then() method (as i pasted above) and it works, however i dont understand how come the checkRegisteredStatus function should finish execution and is popped off from the call stack then how is it being able to modify the result object?
Example:
let result = checkRegisteredStatus(addr)
console.log(result)
the output would be:
> {status:"",registration:""}
when i click the expand sign > it outputs the following:
> {status:"",registration:""}
registrationType: "NotRegistered"
status: false
as far as i understand the value was caught be console.log() when the result object still had empty properties that's why i could expand the object and see its props have different values,i think JS is adding elements from inside that promise that registered before, but the function result obj should be cleaned from the stack (since it returns immediately), how is it adding values to it even though the function is popped from the call-stack?
3- how should i rewrite my function such that it blocks execution until it returns the final result not a promise and not adding up values later.

Why is createReadStream not updating a variable? [duplicate]

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 8 months ago.
I am using fs.createReadStream to read CSV data and it is exhibiting some weird behaviour. I'm very confused as to why this is happening.
I have the following code:
const result = []
fs.createReadStream("path")
.pipe(csv()) //csv parser
.on("data", data => result.push(data))
.on("close", () => console.log(results)) // Showing results correctly here, 5000 rows
console.log(results) // Showing an empty array here []
I don't understand why the results array is going back to empty after the data was added correctly on close.

putting get chrome storage local value to a dict [duplicate]

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I need to get a local storage value outside the call, to use it in another function,
I see this is an async function and outside log gets called first, but cant rly wrap how it works and why I get the value on the second call, but not it the first call.
So the question is how do I get the value outside the call and make First Call work as second call ?
var Credentials = []
chrome.storage.local.get(["Key"], function(result) {
const o = result.Key.email
console.log("this is email", result.key.email)
Credentials.push({"email": result.key.email})
console.log("Second Call",Credentials[0].email)
});
console.log("First Call",Credentials[0])

Undefined global variable when returning data generated in a nested function [duplicate]

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)
Closed 5 years ago.
I have a function that I call which hits an API and returns a JSON, which I am calling getData. Inside that function is a nested function that processes the JSON and saves it to a new variable processedData when it's done making the request from the API.
I'd then like to return that processed JSON, but the console is telling me it's undefined. I didn't declare the variable so it should be treated as global. Why am I still having this issue?
The code won't work with the snippet because the API is only local, but processedData essentially looks like this: {'A': '123'}
function hitAPI() {
var getData = $.get('http://127.0.0.1:5000/myroute');
getData.done(function() {
processedData = (JSON.parse(getData['responseJSON']['data']));
});
return processedData;
};
var x = hitAPI()
console.log(x);

Categories