Reputation: 107
[EDIT BELOW]
Here is the current code:
for(toy of toys) {
fetch(url, {headers: headers})
.then((response) => response.json)
.then((responseJson) => {
<insert toy to database>
})
}
The code above does not post toy properly because the loop completes before the fetch inside does. How do I implement this properly so that I can insert toys with responseJson properties to the database properly? In other words, how can I wait for the fetch to complete before proceeding with the loop?
[PREVIOUS POST]
I have the following code:
function hello(callback1) {
for(var i = 0; i <= 100; i++){
console.log(i)
}
callback1()
}
function callback1() {
console.log("hello")
}
My question is, will callback1
wait for the loop to finish or not?
Here is a second scenario:
function hello() {
for(var i = 0; i < 100; i++){
console.log("apples")
}
for(var i = 0; i < 100; i++){
console.log("peaches")
}
}
Will the output be:
apples
apples
apples
apples
...
peaches
peaches
peaches
...
or
apples
apples
peaches
apples
peaches
...(in any order since they execute at the same time)
I'm having a hard time understanding the flow of react native programs as I am used to linear execution of codes. If you can also suggest readings for dummies, that would be great.
Upvotes: 0
Views: 371
Reputation: 107
I found the answer in this post:
How to make a javascript FOR LOOP wait for certain conditions before looping
In these situations, recursion is more appropriate to use.
Upvotes: 0
Reputation: 7605
As mention in the MDN documentation, the syntax of a for
loop is:
for ([initialization]; [condition]; [final-expression])
statement
Where statement
is:
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;).
This means that everything in the for
loop will be executed before executing the following code.
function hello(callback1) {
for(var i = 0; i <= 10; i++){
console.log(i)
}
callback1()
}
function callback1() {
console.log("hello")
}
hello(callback1);
Upvotes: 1