Will my map function always run first [duplicate] - javascript

This question already has answers here:
Are all javascript callbacks asynchronous? If not, how do I know which are?
(5 answers)
Closed 6 years ago.
Will the map function always finish running before the if statement runs? I want to make sure that the elements in the array are always added up before the if statement runs. Will there ever be a time when the map function doesn't finish running before the if statement starts and so the if statement will not get the true value of the add variable?
var arr = [ '33.3%', '33.3%', '33.3%' ];
var add = 0;
arr.map(function(elem){
add += parseInt(parseFloat(elem)*10000)
});
if (add <= 1001000 && add >= 999000) {
console.log("passed!!")
}

Yes. Unless you have asynchronous requests or multi-threaded operations like WebWorkers, your code is synchronous, i.e. it is executed in strict order.

Array.prototype.map of javascript is synchronous, but if you want an async behaviour you can use nodejs async module.
NodeJS Async Map
var async = require('async');
var arr = ['1','2'];
async.map(arr, getInfo, function (e, r) {
console.log(r);
});
function getInfo(name, callback) {
setTimeout(function() {
callback(null, name + 'new');
}, 1000);
}
http://code.runnable.com/UyR-6c2DZZ4SmfSh/async-map-example-for-node-js

Related

Run a function against each object in an array in parallel? [duplicate]

This question already has answers here:
Wait until all promises complete even if some rejected
(20 answers)
Closed 2 months ago.
I have an array
var array = ["First","Second","Third"]
let i = 0;
I want it to run each object in the array across the same async functions at the same time
for (;i < arbAgainstLength;) {
const first = async () => {
//do some await stuff
}
const second = async (param1, param2) => {
//do other await stuff
}
}
This bot is monitoring price changes, so I'm looking for it to only take action on a specific object at the time that object meets the proper criteria.
So, if First meets the criteria, it will complete the rest of the sequence, but Second and Third will continue to listen.
Then, finally, once the sequence is complete for an object, I'd like to put that object BACK into the async functions.
Currently, and this is probably expected, the function only runs fully if it's the last object in the array
Is it possibly a forEach instead of a for? Or is a promise needed as well?
I have tried async.parallel and promises. If the answer is a promise, I think I may be still trying to grasp how they work exactly.
I think there was a lack of proper verbage in my question but I ended up finding that it was best used as a promise.all with a forEach inside it.
Thanks for all that!

Pause function until promise is resolved [duplicate]

This question already has answers here:
How to wrap async function calls into a sync function in Node.js or Javascript?
(9 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
What is the JavaScript version of sleep()?
(91 answers)
Closed 1 year ago.
My function keeps executing indefinitely, although I would have expected it to resume after 10ms. Is there any way I can flush timeouts while I am waiting for the result? Or at least tell JS to execute / resolve other promises before I return my result?
The simple matter is, I NEED the response before I can continue execution. And I can not put my code in an async block whatsoever. I also can not use 'then' since I need to return the raw result. I thought this hack would work, but nope.
As far as my understanding of JS goes, this simply is not possible, but I would love to know.
let test = function () {
let wait = true;
setTimeout(() => {
wait = false
}, 10);
while (wait);
return wait;
}
you can use async/await , to block the flow of the function
example
const mine = async() => {
console.log("start")
await anotherAsyncFunction()
console.log("done")
}

Run asynchronous JavaScript functions inside a forEach loop synchronously [duplicate]

This question already has answers here:
Resolve promises one after another (i.e. in sequence)?
(36 answers)
Closed 2 years ago.
I'm developing an app and I'm having a problem. I want to run two functions inside a forEach loop, which means for each iteration run both functions once.
This is very simple to do when you think about it, but my functions are asynchronous and my first function needs to finish before the second one executes.
Reason why i made these functions async is that in my app these functions represent an API call.
I will show you a quick example in which i used setTimeout() instead of API calls.
async function f(){
await setTimeout(()=>{
console.log("FIRST")
},1000)
}
async function f2(){
await setTimeout(()=>{
console.log("SECOND")
},3000)
}
for(var i = 0;i < 5; i++){
f()
f2()
}
When I run this the output is:
FIRST
FIRST
FIRST
FIRST
FIRST
SECOND
SECOND
SECOND
SECOND
SECOND
And i need my output to be:
FIRST
SECOND
FIRST
SECOND
FIRST
SECOND
FIRST
SECOND
FIRST
SECOND
Any idea how to achieve this? Would be very helpful.
Wait for the first async function to finish and then call the second one
for(var i = 0;i < 5; i++){
f1().then(res => {
return f2()
}
}
This will not guarantee your desired output, but will guarantee that a call to f2 was done after a call to f1
Note: you could collect all promises into an array and maybe call Promise.all if you want to know when all of them are finished.

How to setTimeout inside a loop [duplicate]

This question already has answers here:
Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
(3 answers)
Closed 6 years ago.
Are you trying to set a timeout to run multiple functions with some delay between them? Is the timeout inside of a for loop? Are your functions all firing off at the same time, and not respecting the timeout, or otherwise causing messy behaviour?
It is intuitive, but incorrect to write it like this:
for (var i = 0; i < moves.length; i++) {
setTimeout(chooseOne(moves[i]), i * 1000 + 1000);
}
SOLUTION:
The solution is to pass the i values to the timeout indirectly, like this. Write the loop, call your timeout function inside the loop and pass that function the i value.
function clickedOne() {
for (var i = 0; i < moves.length; ++i) {
myTimeout(i);
}
}
then in a separate function, set the timeout, pass an anonymous function as your first parameter, inside that function I call my chooseOne function and pass it the unique value for each iteration. Now you can write a comma, and provide the second parameter for setTimeout which is your timeout. My timeout is one second times i, so each function will execute one second after the one that precedes it.
function myTimeout(i) {
setTimeout(function() { chooseOne(moves[i]); }, 1000 * i);
}
I actually don't know why this works and the first method does not.
Try this:
var i = 0;
setTimeout(function(){
if(i < moves.length){
chooseOne(moves[i++]);
}
}, i * 1000 + 1000);

Promises Help - Returning Values [duplicate]

This question already has answers here:
setting a variable to get return from call back function using promise
(2 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 8 years ago.
I have a javascript function where I want to return the value that I get after the return method.
Easier to see than explain
function getValue(file){
var val;
lookupValue(file).then(function(res){
val = res.val;
}
return val;
}
What is the best way to do this with a promise. As I understand it, the return val will return before the lookupValue has done it's then, but the I can't return res.val as that is only returning from the inner function.
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Categories

Resources