0

I can't understand how async and await works. Consider the code below:

    async function getUsername() {
        await setTimeout(function() {
            console.log("username")
        }, 100)
    }
    
    getUsername();
    console.log("password")

I expected the output to be:

   username
   password

instead what I get is:

    password
    username

Thanks in advance.

2
  • 2
    "run this program synchronously" - Then don't use setTimeout O.o Commented Feb 5, 2019 at 7:26
  • 2
    async and await are syntactic sugar to make the work with Promises easier. Your script doesn't use Promises, hence there's no way async/await would change anything for you. Commented Feb 5, 2019 at 7:26

3 Answers 3

1

You can think of await as "unraveling" a Promise. At the moment your code doesn't use a Promise and thus await won't work. Instead, you can wrap your setTimeout in a promise, and resolve your promise once it is complete. Then by using await you can get the resolved value from the Promise (only once it has been resolved (so after 100m/s)) and log it to the console.

async functions will also always return a Promise. Thus, you can use the .then method on your function call to trigger a "callback" once your getUsername function has finished:

async function getUsername() {
    var username = await new Promise(resolve => setTimeout(function() {
        resolve("username");
    }, 100));
    
    console.log(username);
}

getUsername().then(res => {
  console.log("password")
}).catch(er => {
  console.error(er);
});

While the above code works, I prefer to log my content in the resulting .then callback:

const getUsername = async _ => await new Promise(resolve => setTimeout(_ => resolve("username"), 100));

getUsername().then(result => {
  console.log(result);
  console.log("password");
}).catch(er => {
  console.error(er);
});

Or, if you prefer not to use the .then callback and use an async function instead you can use:

const getUsername = async _ => await new Promise(resolve => setTimeout(_ => resolve("username"), 100));

const getUsernameAndPassword = async _ => {
  const username = await getUsername();
  console.log(username);
  console.log("password");
}

getUsernameAndPassword();

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

Comments

0

First of all you can't just await setTimeout as it does not return the promise, you could try to turn contents of that function into one if you want to wait for it's execution

function getUsername() {
    return new Promise(resolve =>{
        setTimeout(function() {
            console.log("username");
            resolve();
        }, 100)
    })
}

On top of that if you have to use .then method, so that promise returned from the function will not be ignored and program will wait for the execution anyway

getUsername().then(()=>console.log("password"));

Comments

0

The async function declaration defines an asynchronous function, which returns an AsyncFunction object.

An asynchronous function is a function which operates asynchronously via the event loop,

using an implicit Promise to return its result. But the syntax and structure of your

code using async functions is much more like using standard synchronous functions.

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

async function name([param[, param[, ... param]]]) {
   statements
}

Reference 1 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Reference2 : https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.