await doesn't wait for the function to end
Unless you're using await
also inside getName
, you don't need to have getName
async, you just need to return a Promise
; since await
works with promises:
const getName = () =>
new Promise(resolve => setTimeout(resolve, 1000, 'xxx'));
async f() {
let name = await getName();
console.log(name);
}
f();
To await a function, that function must return a promise.
You thus need to create a new promise. It will have 2 methods: resolve
, and reject
.
resolve
returns the variable, and is used on success. You can catch its return value by usingpromise.then(value => )
or byawait
ing it.reject
throws an error, and is used on error. You can catch the error by usingpromise.catch(err => )
or by awaiting the async function and wrapping it in a try-catch block.
Here is how your code should look:
const getName = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('xxx');
}, 1000)
})
};
const f = async () => {
name = await getName()
console.log(name)
}
f()