0

I'm learning the world of promise. Everything went well so far, but this time I can't understand why my promise never gets resolved even though it gets throught my conditionnal resolve() (I can see the console.log, but it never gets to the thenable.)

Here is what i'm trying, a typewritter effect that must have dynamic string to type, and wait for one to completed before typing the next one :

<p id="demo"></p>
<p id="demoother"></p>
var zero = 0;
var txt = 'Lorem ipsum dolor sit amet.'; /* The text */
var othertxt = 'Nunc sagittis id tortor non venenatis.';

var container = document.getElementById("demo");
var othrecontainer = document.getElementById("demoother");

var speed = 100; /* The speed/duration of the effect in milliseconds */


function typeWriter(str, node) {
    return new Promise(function(resolve) {
        console.log(str);
        console.log(node.getAttribute('id'));
    
        if (zero < str.length) {
            console.log(zero);
            node.innerHTML += str.charAt(zero);
            zero++;
            setTimeout(typeWriter, speed, str, node);
        }
        
        
        if (zero === str.length) {
            setTimeout(function () {
                resolve(zero);
                console.log('resolved');
            }, speed);
        }
    });
}

typeWriter(txt, container).then((value) => {
    console.log('then');
    typeWriter(othertxt, othrecontainer);
});

I've got the console.log('resolved'), but I never have the console.log('then'). Where am I missing something ? Shouldn't the promise get resolved ?

b3ney
  • 11
  • 3
  • It looks like you're trying to call `.then` on the function, not the promise. Try declaring the promise like a variable (using `let` etc) instead of returning it in a function. – LarryTLlama Jul 12 '23 at 10:45
  • 2
    @LarryTLlama really not sure what you're talking about. OP calls the `typeWriter()` function which returns a promise. They then call `.then()` on that – Phil Jul 12 '23 at 10:46
  • Non-related but why not async/await? – Nico Van Belle Jul 12 '23 at 10:47
  • The problem is that your Promise has logic paths that never resolve. In fact, it only ever resolves when `zero === str.length` which won't happen on the outermost call – Phil Jul 12 '23 at 10:47
  • 3
    You are recursively calling the function. Per recursive call, you are generating a new promise. So you are seeing the "resolved" log because some promise is being resolved, but it's not the one you are listening to. – JSON Derulo Jul 12 '23 at 10:51
  • @Phil then why Op getting console.log('resolved') – Peter Jul 12 '23 at 10:52
  • 1
    @Peter Because somewhere in that recursive `setTimeout` chain, the `zero === str.length` condition becomes true. The issue is resolving those recursive promises so the outermost one eventually resolves – Phil Jul 12 '23 at 10:53

0 Answers0