In Node.js Does all the function with a callback as a input parameter is non-block? [duplicate] - javascript

This question already has answers here:
Are all javascript callbacks asynchronous? If not, how do I know which are?
(5 answers)
Closed 7 years ago.
I am a little confusing about the async function and sync function, how can I determine if it is an async function?
My assumption is all the function which accept a callback is non-block and async, but here is a exception I found:
I found the Array.prototype.forEach is a block function even if it accept a callback as a parameter.
function test(){
[1,2,3,4,5].forEach(function(item){
for(var i =0; i<100000; i++){
console.log('test');
}
});
console.log('end');
}
test();
this function will continue to print test until all the callback finish, it won't return at once to run console.log('end')
really confusing, how can I determine if a function will return at once?

You can use the common sense rule here, is there any need for async in your code? Why do we need to delay the function? All of the array items are available for you, even if they were not, there should be another reader for example which is async then populate the array with avaialble items and then iterate over them. If you need async you will notice this for sure.

Related

returning a value from async/await promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to find a simple example of how to return a value from async/await where the value is easily accessed outside the async function.
Would the following two examples be considered the optimum way to return a value from an async/await function?
In other words, if the value returned from an async/await needs to be saved and used in other parts of the code, what would be the best way to save the value?
this is the easiest example i could find:
async function f() {
return 1;
}
var returnedValue = null; // variable to hold promise result
f().then( (result) => returnedValue = result );
console.log(returnedValue); // 1
or perhaps would it be better to use an object?
async function f(varInput) {
varInput.value = 1;
}
myObject = {} ; myObject.value=null;
f(myObject);
console.log(myObject.value); // 1
thank you.
My answer addresses two subjects here:
1) Async function returns a promise that resolves to a value. So, for instance your first function can be used as per your example. It can also be used like this:
async function() {
const x = await f();
}
2) Immutability - the second solution will work but it makes your funciton "impure". It is not bad in itself, but beware of side effects this might cause (for instance, if you change an app-wide singleton value without other components being notified about it, some part of your app might go out of sync with the data).
Hope this answers your question.

Wait for multiple non nested callbacks [duplicate]

This question already has answers here:
How can I wait for set of asynchronous callback functions?
(8 answers)
Closed 4 years ago.
Say I have two (or more) asynchronous operations op1 and op2 that call a callback function upon completion. How do I best wait for both to complete before starting op3?
I am not able to nest them inside of each other (i.e. first starting op1, then starting op2 inside of op1callback())
(I of course also do not know which of these is going to complete first, but that doesn't really matter I guess)
function op1callback {
}
function op2callback {
}
function op3 {
...
}
The easiest would be to just keep flags about the callbacks state:
let count = 0;
function callback() {
if(++count === 2) op3();
}
op1(callback); op2(callback);
But in the long term it might be beneficial to let the operations return promises, e.g.:
async function op1() {
// Do some async stuff and *await* that
return "something";
}
then you could just do:
Promise.all(op1(), op2()).then(op3);

Can we execute callback to JavaScript's forEach asynchronously? [duplicate]

This question already has answers here:
JavaScript, Node.js: is Array.forEach asynchronous?
(12 answers)
Closed 5 years ago.
var a = [1,2,3,4,5,6,7,8,9,10];
a.forEach(item => {
...
});
console.log('all done');
Is it ever possible in browser or node environment that it console 'all done' before the forEach completes its execution? If yes then when?
No. Your code is synchronous so it can never happen unless you explicitly execute the .forEach function in an async block.
No. forEach is a synchronous function.
It is possible to call asynchronous functions from within it, and they might not have completed, but the loop itself will have done.

$.when().done() is firing the done function before when completes [duplicate]

This question already has answers here:
How do you work with an array of jQuery Deferreds? [duplicate]
(4 answers)
Closed 6 years ago.
I have a page like this:
$(document).ready(function() {
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall());
});
For some reason the finalCall() is firing simultaneous to the three calls surrounded by $.when().
I tried calling a reference to the finalCall() function as in:
$(document).ready(function() {
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall);
});
But even then, it still fires the function before the prior 3 complete.
NOTE: I am not including the functions here as they are not relevant. I just need to know why the finalCall() function would fire simultaneous to then $.when() functions.
Thank you.
$.when does not call your callback at all. You are doing it yourself:
// vv
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall());
// ^^
Change that to
$.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).then(finalCall);
where the function is actually passed into the promise method, and it'll work (assuming your ajax functions return promises).

jQuery function vs handlers [duplicate]

This question already has answers here:
what is the difference between calling function in JavaScript with or without parentheses ()
(4 answers)
Closed 9 years ago.
A simple question from someone trying to learn:
I have this:
$(function(){$("#topFlag").hover(changeFlag, setFlag ); });
function changeFlag(){
//some code
};
function setFlag(){
//somecode
};
And it's all working (now). But what I expected to use was:
$(function(){$("#topFlag").hover(changeFlag(), setFlag() ); });
What's the difference? Why doesn't changeFlag() (with the parens) work? Isn't this a function call? What if I wanted to pass a parameter to the function?
Thanks for any insights (or pointers to documentation I can read). I've already checked out:
http://api.jquery.com/hover/
http://www.w3schools.com/js/js_functions.asp
changeFlag is a function.
changeFlag() calls that function.
You need to pass the function. You don't need to call the function and pass its return value.
When you add braces after a function name , it executes the function
setFlag() ; // calls the function
But you want the function to fire , when you hover over the element
And not at the time of attaching the event
In javascript the functions are also variables, when you pass it as a parameter you want to send the function to execute, if you write this yourFunc() you would be sending the result of that function instead.
To send parameter I use this:
$(function(){$("#topFlag").hover(function(){changeFlag(param1, param2,...)}, function(){setFlag(param1, param2,...)}); });
this creates an anonym function that call your functions.

Categories