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 4 years ago.
I feel something does not fit in my picture, when I try to wrap my head around async-programming. Every JavaScript tutorial says something like:
Every time an expensive operation occurs, we pass a callback function that will be called once we can continue with the processing. We’re not waiting for that to finish before going on with the rest of the program.
How I see it, when we execute some command, we need the result of this code for next command. So, how could async call not to block execution, when we need the result of the async call in rest of our program?
For example such simple code:
var a = 12;
var c = 0;
function sum( data ) {
console.log( data.b + a );
c = data.b + a // global c here
console.log( 'and now we can continue with next command' );
}
verySlowAndExpensiveAsyncCall( a, sum );
console.log( 'can we execute this without waiting previous to finish?' );
console.log( c );
For my procedural mind I feel I can't execute any next command anyway, because I need the value of c to continue. So where is the non-blocking nature here?
My question is maybe not strictly Stack Overflow-questions, but it is fundametal to understand async-programming and I have read a lot of docs and somehow missed this important part: why and when (on which conditions) asynchronous code is non-blocking?
I expect either explanation or source of the explanation as answer.
Related
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.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I'm having problems trying to add rows to the variable x. I have not understood how to return a value from an anonymous function called by another function.
var pgClient = new pg.Client(connectionString);
pgClient.connect();
var query = pgClient.query("SELECT * from sceglie");
var x = [];
query.on("row", function(row,result){
result.addRow(row);
x.push(row);
});
console.log(x);
There is no way to do what you are trying to do. Javascript is a synchronous language in that it executes line by line. So this line:
console.log(x)
Will execute right away. The "on" function will only execute when it is called, so your log statement will always have the empty value.
Link to good article explaining JS environment
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.
This question already has answers here:
Why is setTimeout executing immediately? [duplicate]
(4 answers)
Closed 8 years ago.
I can't find out where is the problem on this code:
<script>
var colori = ['ffffff', 'ffbf00', 'ff4000', '4d79ff', '00c0ff', '00ff3f', 'ff7a4d', '00ff40', 'bf00ff', 'ff0040', 'ffd34d', 'a52a2a', 'bf00ff', '47adcf', '2a82a0' ];
var i;
function CambiaColore(){
i = Math.floor(Math.random() * colori.length);
var colore = '#'+colori[i];
document.body.style.background=colore;
setTimeout(CambiaColore(),2000);
};
CambiaColore();
</script>
Can somebody explain me what's wrong?
setTimeout(CambiaColore(),2000); wrong
setTimeout( CambiaColore, 2000 ); right
Explanation:
SetTimeout's first argument should be function. And you got it. But brackets after function name means its execution (my bad english, ya). Thus in your case it comes to recursion and that's all. Maximum stack calls, error.. So I as understood, you don't need to execute func there but postpone its execution. Correct way to do this I showed above.
Another possibility is to wrap it in an anonymus function:
setTimeout ( function(){ CambiaColore() } , 2000 ) ;
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have been struggling for quiet sometime now with conversion of file chunks to binary data and have come to this point
for(....){
$.when(chunkBinary(chunk[i][j])).done(function(result){ chunkInBinary = result;console.log(chunkInBinary);} )
}
Now I want to be able to use the value chunkInBinary outside the done function. Something like this:
for(....){
$.when(chunkBinary(chunk[i][j])).done(function(result){ chunkInBinary = result;} )
console.log(chunkInBinary);
}
Any suggestions on how I can achieve this?
My chunkBinary function returns a promise.
What you have done is already correct.. by creating a variable without the var keyword, u r literally creating a global variable. So now you can access the chuckinbinary variable outside any function as it is in global scope. This is not good practise as u r cluttering ur global work space.