synchronous and asynchronous loops in javascript

后端 未结 5 1319
我在风中等你
我在风中等你 2020-12-14 06:43

Are loops synchronous or asynchronous in JavaScript? (for, while, etc)

Supposing I have:

for(let i=0; i<10; i++){
    // A (nested stuff...)
}

//         


        
5条回答
  •  轮回少年
    2020-12-14 07:05

    If you place asynchronous loops inside a for...loop and want to stop the loop until each operation ends, you must use the async/await syntax like this.

    async function foo() {
        var array = [/* some data that will be used async*/]
    
        //This loop will wait for each next() to pass the next iteration
        for (var i = 0; i < array.length; i++) { 
            await new Promise(next=> {
                someAsyncTask(array[i], function(err, data){
                    /*.... code here and when you finish...*/
                    next()
                })
            })        
        }
    }
    
    foo().then(() => { /*After foo execution*/ })
    

提交回复
热议问题