1

I have some example code, but I can't figure out why the console is logging things out of order.

    async function myAsyncFunction() {
        setTimeout(() => { console.log("1st"); return "something"; }, 500);
    }
    
    async function mainline() {
        let promise = new Promise((resolve, reject) => {
            setTimeout(() => { console.log("0th"); resolve(); }, 500);
        });
        promise.then(async () => {
            return await myAsyncFunction();
        })
        .then((string) => {
            console.log(string);
            console.log("2nd");
        });
    }

    mainline();

The console logs:

> 0th
> undefined
> 2nd
> 1st

So clearly my mainline isn't waiting to resolve the async function. What did I do wrong?

5
  • Your myasyncfunction isn't returning anything. Your return is inside the setTimeout function. You need to wrap your setTimeout call in a promise. Commented Apr 24, 2020 at 3:06
  • moving the return statement outside the setTimeout() changes undefined to 'something', but it doesn't change where '1st' is logged. I would like '1st' to be logged before '2nd'. Commented Apr 24, 2020 at 3:12
  • You want your asychronous functions to be synchronous? Commented Apr 24, 2020 at 3:14
  • I want them to run in order Commented Apr 24, 2020 at 3:20
  • Just want to note you have two layers of promise function where you call myAsyncFunction. You could have just passed myAsyncFunction directly to the promise, depending on what your actual intent is. Commented Apr 24, 2020 at 3:27

1 Answer 1

2

Your myAsyncFunction isn't returning anything. You need to wrap it in a promise.

function myAsyncFunction() {
return new Promise( (res, rej) => 
    setTimeout(() => { console.log("1st"); res("something"); }, 500) );
}

function myAsyncFunction() {
return new Promise((resolve, reject) => {
    setTimeout(() => { console.log("1st"); resolve("something"); }, 500);
});
}

async function mainline() {
    let promise = new Promise((resolve, reject) => {
        setTimeout(() => { console.log("0th"); resolve(); }, 500);
    });
    promise.then(async () => {
        return await myAsyncFunction();
    })
    .then((string) => {
        console.log(string);
        console.log("2nd");
    });
}

mainline();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.