I am new to Javascript and nodejs. While trying to understand how promises and callbacks work, i tried calling a function in a 'for' loop as shown below. What i was trying to achieve is to print 'i' value every 2 seconds using promises. However, the program waits for 2 seconds and prints i value 3 times and exits.
for(let i = 0; i < 3 ; i++){
func(callback,i);
}
async function func(callback,i){
await callback(i);
}
function callback(i){
return new Promise((res,rej) =>{
setTimeout(()=>{
console.log('i = ',i)
res();
}, 2000);
})
}
Can anybody please help me understand why this is happening?
funcis pretty needless. You could just callcallback(i)directly, with the same result.asynckeyword transformfuncreturns toPromise, and you should useawaitwhenfunccalls (if you want to wait while thisPromisewill be resolved).forloop to pause, you have toawaitthe promise thatfunc()returns.