I am executing the code block below. For the jsfiddle line, click here
async function sleep(time = 1) {
const sleepMilliseconds = time * 1000
return new Promise(resolve => {
setTimeout(() => {
resolve(`Slept for: ${sleepMilliseconds}ms`)
}, sleepMilliseconds)
})
}
async function main() {
let a = [1,2]
a.map(async(el)=>{
let i = 3
console.log(el,i)
while(i>0) {
console.log(el, i, 'main')
console.log(el, i, await sleep(i))
i -= 1
}
})
}
main()
Ideal sequence output would be :-
-
1,3
-
1,3, main
-
1, 3, Slept for: 3000ms
-
1,2, main
-
1,2, Slept for: 2000ms
-
1,1 main
-
1,1 Slept for: 1000ms
-
2, 3
-
2,3, main
-
2, 3, Slept for: 3000ms
-
2,2, main
-
2,2, Slept for: 2000ms
-
2,1 main
-
2,1 Slept for : 1000ms
But I am not getting this output. The output which I am getting both the loops are running parallely I suppose. Can someone suggest how to tweak the program to get the desired output. Thanks in advance from our team @realpensive.
I have tried wrapping the map in await promise.all but that doesn’t seem to help at all.
>Solution :
the .map functionality is exactly what you say it is, parallel, the following has the output you require.
for (const el of a) {
let i = 3
console.log(el,i)
while(i>0) {
console.log(el, i, 'main')
console.log(el, i, await sleep(i))
i -= 1
}
}