简体   繁体   中英

Javascript asynchronous behavior for loops

I was fetching data asynchronously using async/await and then I am running two for loops one after another. So my question is will the for loops overlap each other for big data sets as js is asynchronous and if yes how to solve this? And for what condition loops can overlap?

Actually, I am trying to make a dropdown and its working but I had this doubt.

const createDropdown = async language => {
    let i = 0;
    let listPromise = new Promise((resolve, reject) => {
        db.ref("Products/" + language).on('value', snapshot => {
            resolve(snapshot.val())
        })//Fetching Data
    })

    let list = await listPromise;

    for(i in list)
        dropdown.remove(0)

    for(i in list)
        dropdown.options[dropdown.options.length] = new Option(list[i].name, list[i].name)
}

I am running this code and the for loops are not getting overlapped but is there a condition that it will?

Loops which are put in the code one after the other will never overlap either the code inside the loops are synchronous or asynchronous.

for (var i = 0; i < 10; i++) {
    doSomethingSync()
}



for (var j = 0; j < 10; j++) {
    createPromise().then((res) => {console.log(res))
}


for (var k = 0; k < 10; k++) {
    var res = await createPromise();
    console.log(res);
}

Above, the "I" loop completes all its operations and then the "J" loop, and then the "K" loop.

Here is the order and the details of each operation

  1. The "I" loop serializes the 10 synchronous operations.
  2. The "J" loop create 10 different promises. They maybe resolved in a different order.
  3. The "K" loop creates 10 serialized promises. Each iteration waits until the promise is resolved before going for the net one.

1, 2, and 3 always happen one after the other.

I used this solution to work with axios, with about 1000 requests to a server and works fine, maybe this can be your solution too. In this code you will make a promise of your db.ref and wait for the response then you use that to manipulate.

const createDropdown = async (language) => {
  const listPromise = await Promise.all(
    return await db.ref("Products/" + language).on ('value', snapshot => snapshot.val())
  )

  for(i in listPromise)
        dropdown.remove(0)

  for(i in listPromise)
        dropdown.options[dropdown.options.length] = new Option(list[i].name, list[i].name)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM