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();
setTimeoutO.oasyncandawaitare syntactic sugar to make the work withPromises easier. Your script doesn't use Promises, hence there's no wayasync/awaitwould change anything for you.