Reputation: 104
I am trying to await a recursive method call in javascript. This is my code to start the recursive method:
(async function start() {
await writeText(htmlEditor, 0, time, '#editor');
await writeText(fileSystem, 0, time, '#fileSystem');
await console.log("Hello World");
}).call(this);
This is the recursive method:
function writeText(message, index, interval, to) {
return new Promise(resolve => {
let pre;
if (index < message.length) {
pre = document.getElementById('editor');
pre.scrollTop = pre.scrollHeight;
writeChar(message[index++], to);
setTimeout( function () {
writeText(message, index, interval, to);
}, time);
}
})
}
However, when I use this code, all methods in the start function are called at the same time. I suspect that this is because of the recursive call in the writeText function.
How can I wait for the whole recursive stack to be finished?
Upvotes: 0
Views: 115
Reputation: 7573
Your writeText
function doesn't do any work to give consumers a hook into when execution is actually completed. setTimeout
is used to do a kind of "fire-and-forget" type of execution here.
Try having it return a promise that resolves when the work is actually done:
function writeText(message, index, interval, to) {
let pre;
if (index < message.length) {
pre = document.getElementById('editor');
pre.scrollTop = pre.scrollHeight;
writeChar(message[index++], to);
// wrap the setTimeout in a promise and proxy the result of the recursive call
return new Promise((resolve, reject) => {
setTimeout( function () {
writeText(message, index, interval, to).then(resolve, reject);
}, time);
});
}
// "base case" I guess, return undefined
return Promise.resolve();
}
Upvotes: 2