This is the code I am trying with:
const arr = ['a' , 'b' ,'c', 'd']
const func = async () => {
let i = 0
let interval = setInterval(() => {
let x = arr[i % arr.length]
console.log(x)
if (i === 4 ) {
clearInterval(interval)
}
}, 2000)
}
const another_func = () => {
console.log('logic')
}
const main = async () => {
await func()
another_func()
}
main()
Output :-
logic
a
b
c
d
When I run this problem "logic" gets printed before all the elements of array.
Why should I do print all the elements of array first and only then run the other function and print the logic?
CodePudding user response:
For that, you need to use Promise. Here is my solution:
const arr = ['a', 'b', 'c', 'd']
const func = () => new Promise((resolve, reject) => {
let i = 0
let interval = setInterval(() => {
let com = arr[i % arr.length]
console.log(com)
if (i === 4) {
clearInterval(interval);
resolve('success');
}
}, 2000)
})
const another_func = () => {
console.log('logic')
}
const main = async () => {
await func()
another_func()
}
main()
CodePudding user response:
Your first async
function doesn't use await
, which is already a sign of a problem. setInterval
schedules the execution of the callback, but the setInterval
call itself immediately returns, so your async
function returns, and the implicit promise it returns is resolved. So main
is awaiting a promise that is immediately resolved.
You can typically get a correct implementation by promisifying setTimeout
, i.e. you define a helper function that returns a promise which will resolve after a given delay. With that in place you can create a for
loop with await
in the first async
function:
// Helper function that promisifies setTimeout
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const arr = ['a' , 'b' ,'c', 'd'];
const func = async () => {
for (let i = 0; i < 4; i ) {
await delay(1000);
let x = arr[i % arr.length];
console.log(x);
}
}
const another_func = () => {
console.log('logic');
}
const main = async () => {
await func();
another_func();
}
main();
CodePudding user response:
const arr = ['a' , 'b' ,'c', 'd']
let x;
const func = () => {
for (let i = 0; i < arr.length; i ) {
x = arr[i]
console.log(x)
}
}
const another_func = () => {
console.log('logic')
}
const main = async () => {
await func()
another_func()
}
main()
use async - await only at your main function, remove it from the first function