LearningToProgram
LearningToProgram

Reputation: 23

async await issue promis

my function greetings works but when i try to return a promise to execute things once its done im getting nothing, what am i missing? I have tried putting return resolve() as to make sure the function ends but still nothing, I can´t get the .then() to execute.

 const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv]

    let y = 0

    function greetings() {
        return new Promise((resolve, reject) => {
            if (y == greetingDivs.length) {
                // console.log('resolved')
                resolve('done')
            }
            if (y != greetingDivs.length) {
                setTimeout(() => {
                    let lastDiv = consoleOutput.appendChild(greetingDivs[y])
                        .scrollIntoView(false, { behavior: 'smooth' })
                    y++
                    greetings()
                }, 300)
            }
        })
    }

    greetings().then(() => {
        console.log('hello')
    })

Upvotes: 0

Views: 43

Answers (1)

trincot
trincot

Reputation: 350881

Your code only resolves one promise, while it creates 5. Notably, the first one, the one that greetings() returns, never resolves.

I would suggest promisifying setTimeout, so you have that logic once and for all. Then the looping can be done in an async function with a for loop and await:

const consoleOutput = document.body;

const [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv] = [
    "Hello", "Welcome to this demo", "Hope it suits your case", "Test it", "and enjoy"].map(s => {
    const div = document.createElement("div");
    div.textContent = s;
    return div;
});

const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv];

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function greetings() {
    for (let div of greetingDivs) {
        consoleOutput.appendChild(div)
                    .scrollIntoView(false, { behavior: 'smooth' });
        await delay(300);
    }
}

greetings().then(() => {
    console.log('hello');
});

See ES6 promise for loop for more ideas on how you can create such loops.

Upvotes: 1

Related Questions