0

this is regarding async await and promises. I am not very good at this so I guess i´m missing something. My code is meant to execute the first greetings function which it does. But then only once its done (and only then) it should execute any consecutive functions.

I have tried setting it up in many ways but either the second function doesn't execute or it executes before completion of the first.

Here is my code:

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

    let y = 0

    function greetings() {
        if (y != greetingDivs.length) {
            setTimeout(() => {
                consoleOutput.appendChild(greetingDivs[y])
                y++
            }, 500)
            setTimeout(() => {
                greetings()
            }, 500)
        }
        if (y == greetingDivs.length) {
            return console.log('Greetings are done!')

        }
    }

    function secondFunction() {
        console.log('I have waited')
    }


    async function consoleOn() {
        const result = await greetings()
        if (result) {
            secondFunction()
        }
    }

    consoleOn()
  • 1
    Function `greetings` is not asynchronous (it has to be async or return promise). Almost same example can be [found on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Maybe read up on it first so you can understand it better. – Jax-p Aug 31 '22 at 11:40
  • Something like this might help you find a solution (untested): `async function greetings() { if (y == greetingDivs.length) { console.log('Greetings are done!') return } await new Promise((resolve) => { setTimeout(() => { consoleOutput.appendChild(greetingDivs[y]) y++ resolve() }, 500)}) await new Promise((resolve)=>{ setTimeout(async () => { await greetings() resolve() }, 500)}) } ` – Ben Aston Aug 31 '22 at 11:54

0 Answers0