I have a function called printLetters()
which prints letters after 1000ms. I expected it to print letters one at a time with a 1000ms delay, but it prints all letters at once. It works when I convert it to the async function. However, how do I make printLetters()
resolve each promise with delay without async/await?
const printLetters = (l) => {
for (let i = 0; i < l.length; i++) {
delay(1000).then(() => {
console.log(l[i]);
})
}
}
const printLettersAsync = async(l) => {
for (let i = 0; i < l.length; i++) {
await delay(1000);
console.log(l[i]);
}
}
const delay = (t) => {
return new Promise(res => setTimeout(res, t))
}
const arr = ['a','b','c']
printLetters(arr)
printLettersAsync(arr)
Multiply the number you pass into delay
by the iteration index.
const printLetters = (letters) => {
for (let i = 0; i < letters.length; i++) {
delay(1000 * i).then(() => {
console.log(letters[i]);
})
}
}
const delay = (t) => {
return new Promise(res => setTimeout(res, t))
}
const arr = ['a','b','c']
printLetters(arr)
But there isn't much point to a delay function that you pass a callback into - setTimeout
is easier.
const printLetters = (letters) => {
for (let i = 0; i < letters.length; i++) {
setTimeout(() => console.log(letters[i]), i * 1000);
}
}
const arr = ['a','b','c']
printLetters(arr)
To emulate await
you need to convert your function into a recursive function. What this means is that you need to abandon the for
loop and create your own looping code using recursion:
const printLoop = (l, callback) => {
if (l.length > 0) {
const letter = l.shift();
console.log(letter);
delay(1000).then(() => printLoop(l,callback)); // this is the loop
}
else {
callback(); // we're done
}
}
const printLetters = (l, cb) => {
const letters = Array.from(l); // Copy the array
// to avoid side effects.
// This is optional but
// included to retain similar
// behavior to original code.
printLoop(letters, cb);
}
const arr = ['a','b','c'];
printLetters(arr, () => console.log('done printing letters'));
This is what await
does. It recompiles your code into a structure similar to the example above.