Home > Back-end >  How to make JS stack really "wait" for the ending of an asynchronous function?
How to make JS stack really "wait" for the ending of an asynchronous function?

Time:06-29

I'm learning how Asynchronous JavaScript works, and I'm trying to print to the console the numbers 1 and 2 (in this order). The function that logs 1 has a setTimeout, and as such, the order is always inverted. I know why this happens. I just don't know how to make it work as I would like to. I've tried this:

function first(){
    setTimeout(
            ()=>console.log(1),
            1000
    )

    return Promise.resolve(true)
}

function second(){
    console.log(2)
}


function a(){
    first()
    .then(second())
}

console.log("running...")
a()

and also this:

async function first(){
    setTimeout( 
        ()=>console.log(1),
        2000
    )

    return true            
}

function second(){
    console.log(2)
}


async function a(){
    await first()
    second()
}

console.log("running...")
a()

Both of which print

running...
2
1

The desired output would be

running...
1
2

What am I doing wrong?

CodePudding user response:

Would callbacks not be acceptable?

function first(callback) {
  setTimeout(() => {
    console.log(1);
    callback();
  }, 2000);
}

function second() {
  console.log(2)
}
// When first is completed, second will run.
first(() => second());
console.log("This can run at any time, while we're waiting for our callback.");

CodePudding user response:

Read about Js promises (developer.mozilla.org) here his your code working

function first(){
    return new Promise((resolve)=>{
                        console.log('waiting')
                        setTimeout( ()=>{console.log(1); resolve('waiting finished')}, 2000 )
                        }
                      );
                    }

function second(){
    console.log(2)
}


async function a(){
    await first().then(res => console.log(res))
    second()
}

console.log("running...")
a()

  • Related