Am trying to create a custom asynchronous function asyncFunc in Nodejs that behaves like built in asynchronous JavaScript functions such as setTimeout. However, the function behaves like a synchronous function.
function asyncFunc(i, n){
return new Promise(function(resolve, reject){
// while loop to simulate a long running task
while (i < n){
r = n % i
i = i + 1
}
resolve('success data')
})
}
asyncFunc(1, 1000000000)
.then((data)=> {
console.log(data);
})
// 'test' should be logged to the console immediately on run of script
console.log('test');
I expected the line of code console.log('test') just below the call to asyncFunc to execute immediately and log 'test' to the console instead 'test' gets logged to the console after about 5 seconds followed by 'success data' from asyncFunc.
Is there something am missing about asynchronous functions in JS?